Search code examples
c#.net-4.0multidimensional-arrayintersectionranking

Find intersection of two multi-dimensional Arrays in C# 4.0


Trying to find a solution to my ranking problem.

Basically I have two multi-dimensional double[,] arrays. Both containing rankings for certain scenarios, so [rank number, scenario number]. More than one scenario can have the same rank.

I want to generate a third multi-dimensional array, taking the intersections of the previous two multi-dimensional arrays to provide a joint ranking.

Does anyone have an idea how I can do this in C#?

Many thanks for any advice or help you can provide!

Edit:

Thank you for all the responses, sorry I should have included an example.

Here it is:

Array One:
[{0,4},{1,0},{1,2},{2,1},{3,5},{4,3}]

Array Two:
[{0,1},{0,4},{1,0},{1,2},{3,5},{4,3}]

Required Result:
[{0,4},{1,0},{1,2},{1,1},{2,5},{3,3}]

Solution

  • Given the additional information, I'd argue that you aren't actually working with multidimensional arrays, but instead are working with a collection of pairs. The pair is a pair of doubles. I think the following should work nicely:

    public class Pair : IEquatable<Pair>
    {
        public double Rank;
        public double Scenario;
    
        public bool Equals(Pair p)
        {
            return Rank == p.Rank && Scenario == p.Scenario;
        }
    
        public override int GetHashCode()
        {
            int hashRank= Rank.GetHashCode();
            int hashScenario = Scenario.GetHashCode();
            return hashRank ^ hashScenario;
        }
    }
    

    You can then use the Intersect operator on IEnumerable:

    List<Pair> one = new List<Pair>();
    List<Pair> two = new List<Pair>();
    // ... populate the lists
    List<Pair> result = one.Intersect(two).ToList();
    

    Check out the following msdn article on Enumerable.Intersect() for more information: http://msdn.microsoft.com/en-us/library/bb910215%28v=vs.90%29.aspx