Using this permutation routine as a starting point, I'm attempting to create a routine for a competition in which each contestant partners with every contestant once. I assume I need to iterate a collection popping a pair-up off the list once used, but I'm stuck. Please help.
class Program
{
static void Main(string[] args)
{
var individuals = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8" };
IEnumerable<IEnumerable<string>> teams = GetPermutations(individuals, 2);
/* Rules:
* - each team may play only once
* - a player may not oppose themselves in a match
* A potential result set:
* - 1|2 vs 3|4, 5|6 vs 7|8
* - 1|3 vs 6|8, 2|4 vs 5/7
* - 1|8 vs 2|7, 3|6 vs 4|5
* - 1|7 vs 3|5, 2|8 vs 4|6
* - 1|5 vs 4|8, 2|6 vs 3|7
* - 1|4 vs 6|7, 2|3 vs 5|8
* - 1|6 vs 2|5, 4|7 vs 3|8
*/
Console.ReadKey();
}
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> individuals, int teamSize)
{
int i = 0;
foreach (var individual in individuals)
{
if (teamSize == 1)
yield return new T[] { individual };
else
{
foreach (var result in GetPermutations(individuals.Skip(i + 1), teamSize - 1))
yield return new T[] { individual }.Concat(result);
}
++i;
}
}
}