0

i am trying to get all 2x2 matrices from a big matrix then count how many unique 2x2 matrices whenever i see word "UNIQUE" i think about HashSets the problem is every time i try to add new 2d array to the set it overwrites the old one i can't understand why CODE:

        HashSet<int[,]> set = new HashSet<int[,]>();
        int m = matrix.GetLength(0); int n = 3;
        int[,] current = new int[2, 2];
        int i1 = 0; int i2 = 0;
        while (i1 < m - 1 && i2 < n - 1)
        {
            
            current[0, 0] = matrix[i1][i2];
            current[0, 1] = matrix[i1][i2 + 1];
            current[1, 0] = matrix[i1 + 1][i2];
            current[1, 1] = matrix[i1 + 1][i2 + 1];
            i2++;
            if (i2 == n - 1)
            {
                i2 = 0;
                i1++;
            }
            set.Add(current);
        }
        return set.Count;

putting this line inside the loop int[,] current = new int[2, 2]; makes it add all matrices even if they have the same content

EDIT: the input :

      Int[][] input = new int[][] 
      {new int[]{1, 2, 1},
      new int[]{2, 2, 2},
      new int[]{2, 2, 2},
      new int[]{1, 2, 3},
      new int[]{2, 2, 1}};
  • You'll also need an `IEqualityComparer` to pass to the hashset constructor, otherwise you'll be comparing reference equality of the array and you won't get unique values. – DiplomacyNotWar May 01 '22 at 14:20

0 Answers0