4

I have this multidimensional array:

int[][] x;

So, for each position I have:

x[0] = [10,10,10,10,10]
x[1] = [10,10,10,10,10]
x[2] = [10,10,10,10,10]
x[3] = [5,5,5]
x[4] = [5,5,5]
x[5] = [10,5,5,5]
x[6] = [10,5,5,5]
x[7] = [5,5,5]

I want group like this:

z[0] = 3 x [10,10,10,10,10]
z[1] = 3 x [5,5,5]
z[2] = 2 x [10,5,5,5]

Or if is possible:

y[0] = 3 | 5x10
y[1] = 3 | 3x5 
y[2] = 2 | 1x10, 3x5
ekad
  • 14,436
  • 26
  • 44
  • 46
filipewan
  • 59
  • 6

1 Answers1

5

Well C#'s LINQ has a .Distinct() extension method that returns the list of distinct elements. The problem is that two arrays are not seen as equal if they have the same elements (in the same order). So one first needs to design an IEqualityComparer<T>:

public class ArrayEqual<T> : IEqualityComparer<T[]> {

    public bool Equals(T[] x, T[] y) {
        return Enumerable.SequenceEqual(x,y);
    }

    public int GetHashCode (T[] x) {
        int hash = 0;
        foreach(T t in x) {
            hash = 3*hash ^ t.GetHashCode();
        }
        return hash;
    }

}

And then call it with:

int[][] z = x.Distinct(new ArrayEqual<int>()).ToArray();

If you want to generate tuples of the count with an array, you can do this with:

Tuple<int,int[]>[] z = x.GroupBy(x => x,new ArrayEqual<int>()).Select(x => new Tuple<int,int[]>(x.Count(),x.Key)).ToArray();

The Enumerable.SequenceEqual is borrowed from here. The GetHashCode method I've invented myself, and can probably be improved. After all this is only a short demo.

Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555