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?