I am trying to get only distinct coordinates meaning coordinates (6,7) and (7,6) are the same. How can I go over an array and only get distinct coordinates? So basically I need all of the combinations of coordinates from an int[][] array.
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 +
'}';
}
}
The output I would like to have:
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}
...
But at the moment I get all of the possible variations of the coordinates. How can I change the code to get the result I need?
equalsandhashCodeofCoordsand use aHashMapto keep track of coordinates that you have already seen. TheequalsandhashCodeimplementations should define some order in whichxandyare considered (e.g. always consider the smaller value ofxandyfirst). For example,hashCodecould look something like{ 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(); } }coordinatesarray got to do with question?