简体   繁体   English

在二维数组中查找重复项

[英]Finding duplicates in a 2D array

Lets say I have a 2D array with values called int map[][] = new int[10][10] .假设我有一个二维数组,其值称为int map[][] = new int[10][10] The default values in the array are 0 's and some values in map[][] can change to -1 , -2 , -3 , etc.数组中的默认值为0并且map[][]中的一些值可以更改为-1-2-3等。

Let's say the values in the 2D array are changing constantly and I want to my program to perform something when there are for example, 3 of -3 's found or if 2 of -2 's found, etc.假设 2D 数组中的值不断变化,我希望我的程序在例如找到3-3或找到2-2等时执行某些操作。

I have no idea how to implement this.我不知道如何实现这一点。 Please can someone help?请问有人可以帮忙吗?

You need to build a frequency map for the input 2D array, by iterating the array and adding to the map the values which are not equal to 0.您需要为输入二维数组构建频率 map,方法是迭代数组并将不等于 0 的值添加到 map。

It is convenient to use Stream API for this, where the input array is converted into a IntStream of int numbers, which is filtered and the frequencies are counted for non-zero numbers.为此使用 Stream API 很方便,其中输入数组被转换为int数字的IntStream ,对其进行过滤并计算非零数字的频率。

When the frequency map is ready, the values which occur only once may be excluded.当频率 map 准备好时,可以排除只出现一次的值。

static Map<Integer, Integer> calculateFrequency(int[][] arr) {
    return Arrays
        .stream(arr) // Stream<int[]>
        .flatMapToInt(a -> Arrays.stream(a)) // IntStream
        .boxed() // Stream<Integer>
        .filter(x -> x != 0) // do not count 0
        .collect(Collectors.groupingBy(x -> x, Collectors.summingInt(x -> 1))); // build the map
}

static Map<Integer, Integer> removeSingles(Map<Integer, Integer> frequencyMap) {
    return frequencyMap
        .entrySet()
        .stream() // Stream<Map.Entry<Integer, Integer>>
        .filter(x -> x.getValue() > 1) // do not count single
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // build the map
}


// test
int[][] arr = new int[10][10];
arr[0][1] = -1;
arr[3][2] = -1;
arr[7][7] = -1;
arr[1][2] = -2;
arr[8][5] = -3;
    
Map<Integer, Integer> frequencyMap = calculateFrequency(arr);
System.out.println("frequencyMap: " + frequencyMap);
    
System.out.println("without singles: " + removeSingles(frequencyMap));

output: output:

frequencyMap: {-1=3, -2=2, -3=1}
without singles: {-1=3, -2=2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM