【问题标题】:All possible combinations of int[][] arrayint[][] 数组的所有可能组合
【发布时间】:2018-12-03 18:09:04
【问题描述】:

我试图只获得不同的坐标,这意味着坐标(6,7)(7,6) 是相同的。我怎样才能遍历一个数组并且只获得不同的坐标?所以基本上我需要来自int[][] 数组的所有坐标组合。

ArrayList<Coords> coordinateList = new ArrayList<>();
int[][] coordinates = { {56,80}, {32,26}, {47,85}, {3,4}, {10,19}};


public void findDistinct(int[][] coordinates){
    for (int i = 0; i < coordinates.length; i++) {
        for (int j = 0; j < coordinates.length - 1 ; j++) {
            if (i == j) continue;
            Coords coords = new Coords(i, j);
            if(! coordinateList.contains(coords)){
                coordinateList.add(coords);
            }
        }
    }
    for(Coords coords: coordinateList){
        System.out.println(coords);
    }
}


public class Coords{

    private final x;
    private final y;

    public Coords(x,y) {
        this.y = y;
        this.x = x;
    }

    @Override
    public String toString() {
        return "Coords{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

我想要的输出:

Coords{x=0, x=1}
Coords{x=0, x=2}
Coords{x=0, x=3}
Coords{x=0, x=4}
Coords{x=1, x=2}
Coords{x=1, x=3}
Coords{x=1, x=4}
Coords{x=2, x=3}
Coords{x=2, x=4}
...

但目前我得到了坐标的所有可能变化。如何更改代码以获得我需要的结果?

【问题讨论】:

  • 您可以覆盖CoordsequalshashCode 并使用HashMap 来跟踪您已经看到的坐标。 equalshashCode 实现应该定义一些考虑 xy 的顺序(例如,总是首先考虑 xy 的较小值)。例如,hashCode 可能类似于 { if (this.x &lt; this.y) { return (Integer.toString(this.x) + Integer.toString(this.y)).hashCode(); } else { return (Integer.toString(this.y) + Integer.toString(this.x)).hashCode(); } }
  • coordinates 数组的内容和问题有什么关系?

标签: java arrays combinations


【解决方案1】:
for (int j = 0; j < coordinates.length; j++) 

应该是

for (int j = i + 1; j < coordinates.length; j++)

这样你也不再需要检查if (i == j)

【讨论】:

  • 但是当我这样做时,我似乎缺少 4 个组合。使用我在这里给出的 5 个coordinates,我只得到 6 个组合,但应该有 10 个。
  • 啊,你还需要j &lt; coordinates.length(或j &lt;= coordinates.length - 1)。
  • @Richard 有了这个简化的逻辑,就不需要检查列表是否包含坐标,所以检查if(! coordinateList.contains(coords)) 是无关紧要的
  • @JoakimDanielson 是的,我删除了所有额外的检查,因为没有它们代码可以正常工作
【解决方案2】:

coordinateList.contains(coords) 将检查 obj 哈希码是否匹配。如果你想要 contains 方法来检查两个对象的坐标是否匹配,你已经为 Class Coords 实现了 hashcode 和 equals 方法。

由于您想要一个唯一的坐标列表,请考虑使用 Set 数据结构而不是列表,因为包含是费用操作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2022-01-18
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多