简体   繁体   English

如何比较 2 个不同大小的二维数组?

[英]How do I compare 2 different sized 2D arrays?

The first 2D array is第一个二维数组是

[[1, 10], [0, 4], [1, 1]]

The second 2D array is第二个二维数组是

[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]

How do I find if they have values overlapping in the 2nd column?如何确定它们在第二列中是否有重叠的值?
And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?找到重叠后,如何用第一个二维数组替换第二个二维数组中的元素?

For example:例如:
[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array.第一个二维数组中的[1, 10]与第二个二维数组中的[0, 10]具有相同的第二列值。 Then, I replace [0, 10] with [1, 10] .然后,我将[0, 10]替换为[1, 10]

    int[][] first = {{1, 10}, {0, 4}, {1, 1}};
    int[][] second = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}, {0, 10}};

    // first lets build a map for easy lookup of values 
    // produces map {1=1, 4=0, 10=1}
    final Map<Integer, Integer> map = Stream.of(first)
            .collect(Collectors.toMap(key -> key[1], value -> value[0]));

    // then we can do simple loop
    for (int[] pair : second) {
        // and if it contains the key (second column)
        if (map.containsKey(pair[1])) {
            // then we can just replace the value
            pair[0] = map.get(pair[1]);
        }
    }
public static void main(String args[]) {
  int arr1[][] = {{1, 10}, {0, 4}, {1, 1}};
  for (int i = 0; i < arr1.length; i++)
  {
    int temp = arr1[i][1];
    if (temp > 0 && temp <= 10)
    {
      arr1[i][0] = 0;
    }
  }
}

If duplicate key found in first 2D array, the last one will override the previous value.如果在第一个二维数组中发现重复键,最后一个将覆盖之前的值。 Simple for loop for the beginner of Java. Java 初学者的简单 for 循环。

public static void main(String[] args) {
    int[][] firsts = {{1, 10}, {0, 4}, {1, 1}};
    int[][] seconds = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}, {0, 10}};

    for(int[] secondRow : seconds) {
        for(int[] firstRow: firsts) {
            if(firstRow[1] == secondRow[1])
                secondRow[0] = firstRow[0];
        }
    }       

    // Use for displaying updated result only
    for(int[] secondRow : seconds)
        System.out.println("[" + secondRow[0] + ", " + secondRow[1] + "]");     

}

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

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