3

I have a List of objects named Team and I want the optimal way to get all the possible pairs of objects. I've written an example:

public void GenerateMatches(Team team)
    {

        for(int i = 0; i < team.Count-1; i++)
        {
            for (int j = i + 1; j < team.Count; j++)
            {
                Console.WriteLine("Match:" + team[i].Name + " vs " + team[j].Name);
            }
        }
    }

This is far from optimal but it works. Any better ideas?

6
  • Team1 vs Team2 is the same as Team2 vs Team1 I assume that is what you meant Jul 22, 2016 at 15:23
  • 6
    Why is this "far from optimal"? What have you tried?
    – CodeCaster
    Jul 22, 2016 at 15:23
  • 7
    Willy-nilly you have to enumerate N * (N - 1) / 2 items for all possible pairs; your solution is optimal in this meaning Jul 22, 2016 at 15:25
  • You send a team, and then iterate it as teams? Jul 22, 2016 at 15:29
  • @FirstStep sorry for that copy paste error Jul 22, 2016 at 16:45

2 Answers 2

2

Here is the solution:

You will need to iterate Teams and take pairs of currentTeam with all the next indexes:

    List<int> MyList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9}; // sample input

    List<KeyValuePair<int, int>> MyPairs = new List<KeyValuePair<int, int>>(); // prepare final result

    for (int i = 0; i < MyList.Count; i++)
        for (int j = i + 1; j < MyList.Count; j++)
            if(j < MyList.Count)
                MyPairs.Add(new KeyValuePair<int, int> (MyList[i], MyList[j]));

Then to display:

    foreach (var pair in MyPairs)
        Console.WriteLine(pair.Key +" vs "+ pair.Value);

Part of the output:

enter image description here

9
  • Your missing some brackets ")"
    – Jamie Rees
    Jul 22, 2016 at 15:38
  • Second condition should be j < Team.Count, or this will just loop until it throws. It will also create matches where a team plays itself, unlike the original code. Jul 22, 2016 at 15:42
  • @CharlesMager Another ops :) I type fast.. Thanks for pointing that out :) Should work now Jul 22, 2016 at 15:58
  • @JamieR you ' re missing a ' :P Thanks for the edit ;) Jul 22, 2016 at 16:00
  • 1
    Haha! damn you @FirstStep !
    – Jamie Rees
    Jul 22, 2016 at 16:01
1

The optimal running time is n(n - 1)/2, since this is the number of ordered pairs.
Your solution is optimal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.