簡體   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