0

I have some problems with comparison of matrix elements. Here is the code:

int coll = 0;
for (int i = 0; i < 9; i++)
{
    for (int j = 0; j < 9; j++)
    {
        int tmp = 0;
        for (int k = 0; k < 9; k++)
        {
            if (matrix[i, j] == matrix[i, k])
            {
                tmp++;
                Console.WriteLine("{0},{1} coll {2},{3}-al", i, j, i, k);
            }
            coll += tmp;
        }

    }
}

The code wants to compare the elements of an array called matrix. When 2 elements in a column are the same, I'll increase the tmp value. At the end coll will be increased by the number of the collisions of the actual element of the array. The problem is that the program will find only the collisions of the element with itself. For example, for a matrix like

1234
1342
2341
2413

the 0:0 position will collide only with itself and not with 1:0. Can anyone tell me why?

Andrei V
  • 7,306
  • 6
  • 44
  • 64

1 Answers1

0

Try this logic:

class Program
{
    static void Main(string[] args)
    {
        int[,] matrix=new int[,] {
            { 1, 2, 3, 4 },
            { 1, 3, 4, 2 },
            { 2, 3, 4, 1 },
            { 2, 4, 1, 3 } };

        // This returns the #of collisions in each column
        Debug.WriteLine(CheckColumn(matrix, 0));    // 2
        Debug.WriteLine(CheckColumn(matrix, 1));    // 1
        Debug.WriteLine(CheckColumn(matrix, 2));    // 1
        Debug.WriteLine(CheckColumn(matrix, 3));    // 0
    }

    static int CheckColumn(int[,] matrix, int column)
    {
        int[] data=new int[matrix.GetLength(0)];
        for(int i=0; i<data.Length; i++)
        {
            data[i]=matrix[i, column];
        }
        var hist=data.GroupBy(i => i)
            .OrderByDescending(g => g.Count())
            .Select(g => new { Num=g.Key, Dupes=g.Count()-1 })
            .Where(h=>h.Dupes>0);

        return hist.Count()>0?hist.Sum(h=>h.Dupes):0;
    }
}

I used code from https://stackoverflow.com/a/10335326/380384

Community
  • 1
  • 1
John Alexiou
  • 28,472
  • 11
  • 77
  • 133