Assuming that B[] is longer than A[]
, I'm trying to figure out a way to count the number of times all the elements of A[]
occurs in B[]
.
So say a[]{A,B}
& B[A,B,C,A,C,A,B,B,A,B]
It would return 3
Assuming that B[] is longer than A[]
, I'm trying to figure out a way to count the number of times all the elements of A[]
occurs in B[]
.
So say a[]{A,B}
& B[A,B,C,A,C,A,B,B,A,B]
It would return 3
Here's a generic method that counts occurrences of one array within the other:
public static <T> int countOccurrences(T[] hayStack, T[] needle) {
int foundCount = 0;
for (int i = 0; i <= hayStack.length - needle.length; i++) {
boolean found = true;
for (int j = 0; j < needle.length; j++) {
if (!Objects.equals(hayStack[i + j], needle[j])) {
found = false;
break;
}
}
if (found) {
foundCount++;
}
}
return foundCount;
}
And here's a test class to go with it:
public class ArrayzTest {
@Test
public void countOccurrences_whenNeedleEmpty_returnsHaystackLength(){
assertThat(Arrayz.countOccurrences(hayStack(), emptyArray()), is(hayStack().length));
}
@Test
public void countOccurrences_whenHaystackEmpty_returnsZero(){
assertThat(Arrayz.countOccurrences(emptyArray(), hayStack()), is(0));
}
@Test
public void countOccurrences_whenHaystackHasNeedles_countsOccurrences(){
assertThat(Arrayz.countOccurrences(hayStack(), needle()), is(3));
}
private Integer[] needle() {
return new Integer[]{1,2,3};
}
private Integer[] hayStack() {
return new Integer[]{1,2,3,1,2,3,1,2,3};
}
private Integer[] emptyArray() {
return new Integer[0];
}
}