0

I am making an implementation of the game Hexic. The game is centered around making clusters of Hexagons in order to remove them from the board. I have found a way to identify the coordinates of every hexagon that is part of a cluster in order to add them to a set. Some of these will be identified twice, but I only want every coordinate to be saved once which is why I chose a set.

The issue is that the coordinates get added to the set twice anyway.

The following is the relevant code:

Instantiating the set:

private Set<int[]> clusters = new HashSet<>();

The nested loop for identifying the clusters:

void findClusters() {
        for (int i = 0; i < NOOFCOLUMNS; i++) {
            for (int j = 1; j < NOOFROWS; j++) {
                Color color = hexagons[i][j].color;
                int row = j-i%2; // do not remove, else magic number
                if ((hexagons[i][j-1].color == color)) {
                    if ((i>0)&&(hexagons[i-1][row].color==color)) { addCluster(i, j, -1); }
                    if ((i<9)&&(hexagons[i+1][row].color==color)) { addCluster(i, j, +1); }
                }
            }
        }
    }

The function for adding the coordinates to the set:

void addCluster(int i, int j, int x) {
        clusters.add(new int[] { i, j });
        clusters.add(new int[] { i, j-1 });
        clusters.add(new int[] { i+x, j-i%2 });
    }

Thanks in advance!

Jonas
  • 1
  • Using a linkedhashet instead of a hashset has worked for me – Shivansh Potdar Oct 13 '20 at 12:57
  • You have to use a set of objects that have proper `equals()` and `hashCode()` implementations. Arrays only have object equality. – RealSkeptic Oct 13 '20 at 12:57
  • @RealSkeptic, do you happen to know any applicable objects/data types that possess this quality on the top of your head? – Jonas Oct 13 '20 at 13:32
  • You can write your own, though many libraries have something like `Pair` or `Tuple`. – RealSkeptic Oct 13 '20 at 13:41
  • I did make my own class and overrode(?) the equal and hashCode methods and it works as intended now. Thank you! Also, as someone who mainly used Python before I find it funny that the answer for any given problem I run into in Java is usually "create your own class". – Jonas Oct 13 '20 at 15:52

0 Answers0