【发布时间】: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}
...
但目前我得到了坐标的所有可能变化。如何更改代码以获得我需要的结果?
【问题讨论】:
-
您可以覆盖
Coords的equals和hashCode并使用HashMap来跟踪您已经看到的坐标。equals和hashCode实现应该定义一些考虑x和y的顺序(例如,总是首先考虑x和y的较小值)。例如,hashCode可能类似于{ if (this.x < 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