繁体   English   中英

在二维数组中查找多个匹配数字并返回 boolean 数组

[英]finding multiple matching numbers in a 2d array and returning a boolean array

我在创建一个将二维 integer 数组作为输入的方法时遇到了问题。 output 将是第二个二维数组,其元素数量与第一个数组的相应行相同,这次元素的类型将为布尔值。 output 的值将多次对应数组中存在的值。

该方法应使用searchForMultiple方法。

在这里我提供了一个例子:

如果inputArray是该方法的 output,则该方法将是以下 boolean 数组: [[ 4, 9], [ 9, 5, 3]]因为 9 在输入数组中出现两次,所以 output 中的两个位置对应于这两个实例为真,所有其他值只出现一次,因此它们的值为假,如下所示: [[ false, true ], [ true, false, false]]

代码如下:

class SearchAndPrint{
    public static void main(String[] args){
        int[][] testCase = 
        {{4, 9, 10, 9},
            {5, 4, 7, 10, 11},
            {4, 2}};
        System.out.println("The test case array: ");
        for (int i=0; i<testCase.length; i++){
            for (int j=0; j<testCase[i].length; j++){ 
                System.out.print(testCase[i][j]+" ");
            }
            System.out.println();      
        }        
        boolean[][] founds = gridOfMultiples(testCase);
        System.out.println("Positions with repeated numbers are marked below: ");
        printGrid(founds);
    }
    public static boolean[][] gridOfMultiples(int[][] testCase){
        boolean [][] gridOfMultiples = new boolean[testCase`.length];
        for(int i = 0; i<testCase.length; i++){
            for(int j =0; j<testCase[i].length; j++){
                if(testCase[i][j]==testCase[i][j]){
                    gridOfMultiples[i][j]= true;
                }
                else
                gridOfMultiples[i][j]= false;
            }
        }
    }
    public static boolean searchForMultiple(int[][] inputArray, int search){
    }
    public static void printGrid(boolean[][] inputGrid){
    }
}

似乎您的代码可以像这样简单,不需要searchForMultiple()方法,这无论如何都会对性能不利。

public static void main(String[] args) {
    int[][] testCase = { {4, 9, 10, 9},
                         {5, 4, 7, 10, 11},
                         {4, 2} };
    System.out.println(Arrays.deepToString(testCase));
    boolean[][] founds = gridOfMultiples(testCase);
    System.out.println(Arrays.deepToString(founds));
}
public static boolean[][] gridOfMultiples(int[][] testCase) {
    Map<Integer, Long> frequency = Stream.of(testCase)
            .flatMapToInt(IntStream::of)
            .boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    boolean[][] founds = new boolean[testCase.length][];
    for (int i = 0; i < testCase.length; i++) {
        founds[i] = new boolean[testCase[i].length];
        for (int j = 0; j < testCase[i].length; j++)
            founds[i][j] = frequency.get(testCase[i][j]) > 1;
    }
    return founds;
}

Output

[[4, 9, 10, 9], [5, 4, 7, 10, 11], [4, 2]]
[[true, true, true, true], [false, true, false, true, false], [true, false]]

暂无
暂无

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

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