Java - 计算数组B中数组A的元素的出现次数

时间:2018-03-08 22:04:34

标签: java arrays

假设B []超过A[],我正试图找出一种方法来计算A[]B[]的所有元素出现的次数。< / p>

所以说a[]{A,B}&amp; B[A,B,C,A,C,A,B,B,A,B]

它将返回3

1 个答案:

答案 0 :(得分:0)

这是一个通用方法,用于计算一个数组在另一个数组中的出现次数:

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

这是一个测试课:

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

}