简体   繁体   中英

All possible combinations of int[][] array

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?

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

should be

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

That way you also no longer need to check if (i == j)

coordinateList.contains(coords) is going to check if the obj hashcode match or not. If you want contains method to check if coordinates of the two object matches or not, You have implement hashcode and equals method for Class Coords.

Since You want a unique list of coordinates, consider using Set data structure instead of list since contains is expense operation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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