比较两个1列2d阵列

时间:2016-11-02 22:20:48

标签: java arrays

我有一个二维数组

  0 1  0  
  0 *  0  
  0 *  0    
  0 2  0  
  0 *  0    

我改变了这个

0 * 0      
0 * 0     
0 * 0    
0 1 0    
0 2 0    

通过这样做

    Dot[][] tempDot = dotArray;
  ArrayList<Descriptor> movedList = new ArrayList<Descriptor>();
  for(int j=0; j<this.getHeight(); j++){
for (int i=this.getHeight()-1; i>0; i--){
    if(dotArray[i][col] == null){
        dotArray[i][col] = dotArray[i-1][col];
        dotArray[i-1][col] = null;
    }
}
        }

现在我想弄清楚如何将第一列中的第二列与第二列中的第二列进行比较。我必须返回一个“描述符”对象,该对象包含原始位置,任何非空的向下移动。我已经尝试嵌套for循环来检查每个循环中的第一个值,然后在第二个循环中查找第一个值,但这不起作用。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

如果Descriptor定义如下,

private class Descriptor {
    Descriptor(int from, int to, Dot[] dots) {
        this.from = from;
        this.to = to;
        this.dots = dots;
    }

    public int from;
    public int to;
    public Dot[] dots;
}

你可以这样做。

    // Store original location(index) of each row.
    Map<Dot[], Integer> originLocMap = new HashMap<Dot[], Integer>();
    for (int i = 0; i < tempDot.length; i++) {
        originLocMap.put(tempDot[i], i);
    }

    // Sort rows by second column (dot[*][1])
    for (int i = tempDot.length - 1; i > 0; i--) {
        if (tempDot[i][1] != null) {
            continue;
        }

        for (int j = i - 1; j >= 0; j--) {  
            if (tempDot[j][1] != null) {
                Dot[] temp = tempDot[i];
                tempDot[i] = tempDot[j];
                tempDot[j] = temp;
                break;
            }
        }
    }

    // Collect location change data
    ArrayList<Descriptor> movedList = new ArrayList<Descriptor>();
    for (int i = tempDot.length - 1; i >= 0; i--) {
        if (tempDot[i][1] == null) {
            break;
        }

        Dot[] dots = tempDot[i];
        int from = originLocMap.get(dots);
        Descriptor descriptor = new Descriptor(from, i, dots);
        movedList.add(descriptor);
    }


    Iterator<Descriptor> it = movedList.iterator();
    while (it.hasNext()) {
        Descriptor d = it.next();
        System.out.println(d.from + " ==> " + d.to);
    }