-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

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • And your question is... – Joe C Mar 08 '18 at 22:10
  • Why 3 and not 4? `A1,B1,C,A2,C,A3,B2,B3,A4,B4` I can see: 4 `A` and 4 `B`. They are not in order, but they appear 4 times both of them (Added numbers to count each) – Frakcool Mar 08 '18 at 22:11
  • @Frakcool every `A` immediately followed by a `B`, and there's only three of those in the specified example. – Ousmane D. Mar 08 '18 at 22:13
  • @Aominè it's not specified in the description, it only says: *"I'm trying to figure out a way to count the number of times all the elements of `A[]` occurs in `B[]`."* So, all elements of `A[]` appear 4 times in array `B[]`. That's why I'm asking why. If they should be in order, then yes, it's 3. But unless OP clarifies it's still something to take note (at least for me) – Frakcool Mar 08 '18 at 22:14
  • Possible duplicate of [How to count the number of equal values in two arrays?](https://stackoverflow.com/questions/15666650/how-to-count-the-number-of-equal-values-in-two-arrays) –  Mar 09 '18 at 00:57
  • Sorry (haven't slept in several days), should have specified that I meant all elements of A[] in that exact order in B[] – Kevin Wakatama Mar 09 '18 at 11:51

1 Answers1

0

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];
    }

}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588