Reputation: 16050
Let's say I have the vector vals
and a number n
:
boolean[] vals = new boolean[]{false, true, true, false, false,
true, false, true, true};
int n = 2;
I need to define if the vector vals
has n
sequential nodes equal to true
. If it has, then I want to get index positions of these nodes. For instance, in the above-given example, the answer is:
{{1,2},{7,8}}
Upvotes: 2
Views: 138
Reputation: 421040
Here's one approach.
public static int[][] subSeqs(boolean[] vals, int n) {
List<int[]> result = new ArrayList<>();
int i = -1;
for (int j = 0; j <= vals.length; j++) {
boolean b = j == vals.length ? false : vals[j];
if (b && i == -1) { // going from false to true
i = j;
} else if (!b && i != -1) { // going from true to false
if (j-i >= n)
result.add(new int[] { i, j-1 });
i = -1;
}
}
return result.toArray(new int[result.size()][]);
}
Basically i
is a "state" variable updated during iteration over the array.
i
is -1
, we're in a false
sequencei
is a non-negative number it represents the index of the first true, in the current true sequence.So, when we switch from false
to true
we set i
to the current index, and when we switch from true
to false
we check if the just-finished true
sequence was >= n
.
Upvotes: 2