Home > Software engineering >  How do I check if any elements in a 2d array are equal?
How do I check if any elements in a 2d array are equal?

Time:09-11

I have a 2d array: {{1, 2, 2}, {3, 1, 4}}.

I'm trying to make a function to traverse said array, check if each individual element is equal to any other element in the array and then add the number to a list, but I'm stuck.

This is what I've tried so far:

    static List<int> FindDuplicates(int[,] array, int totalRows, int totalCols)
    {
        List<int> duplicates = new List<int>();
        int row = 0, col = 0;

        //Loops until all elements have been checked
        while (true)
        {
            for (int i = 0; i < totalRows; i  )
            {
                for (int j = 0; j < totalCols; j  )
                {
                    if (array[row, col] == array[i, j])
                    {
                        //Makes sure matching element is only recorded once
                        if (!duplicates.Contains(array[row, col]))
                            duplicates.Add(array[row, col]);
                    }
                }
            }

            //Moves to next element in the array
            col  ;
            if (col > totalCols)
            {
                col = 0;
                row  ;
                if (row > totalRows)
                    break;
            }
        }

        return duplicates;
    }

Edit: My expected result is {1, 2}, but I keep getting a list with all the elements. The issue with my function is that it checks the starting element with itself and adds it to the list. Any suggestions on how to avoid that?

CodePudding user response:

If you want to find duplicates, i.e. having

{
 { 1, 2, 2 }, 
 { 3, 1, 4 }
}

the desired result is List<int>

{ 1, 2 }

you can use Linq:

using System.Linq;

...

static List<int> FindDuplicates(int[,] array) {
  return array
    .OfType<int>()
    .GroupBy(item => item)
    .Where(group => group.Count() > 1)
    .Select(group => group.Key)
    .ToList();
}

No Linq solution can be a loop with HashSet:

static List<int> FindDuplicates(int[,] array) {
  List<int> result = new List<int>();
  
  HashSet<int> known = new HashSet<int>();
  HashSet<int> duplicates = new HashSet<int>();

  foreach (int item in array)
    if (!known.Add(item))
      if (duplicates.Add(item))
        result.Add(item);

  return result;
}

Note, that we don't need int totalRows, int totalCols: we can either enumerate items or use array.GetLength(0) and array.GetLength(1)

  • Related