3

I have a list with some values, lets say 1 2 3 4 5 6

I need to pair them up like this: 12 13 14 15 16 23 24 25 26 34 35 36 45 46 56

Basically, I need to mix them all up to create unique sets of values.

Do you have any ideas on how to create a new list like this?

Thank you for your input!

Nikita Silverstruk
  • 1,097
  • 1
  • 20
  • 42
  • 1
    what about 21, 31, 32, 41, 42 & 43? – spender Oct 01 '12 at 00:29
  • Looks like the OP just wants combinations, in this case there are C(6,2) = 15 of them. Does C# have something built in for that? This is trivial in Python and other languages with list comprehensions, so I would imagine C# does too.... – Ray Toal Oct 01 '12 at 00:32
  • Looks like combinations of k elements from n, i.e k = 2, n = 6 http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n – Luke Hutton Oct 01 '12 at 00:34
  • Value is not necessary a number. Values could be strings in my case.. Also, 6 is not the limit - it may vary. I just simplified a bit. – Nikita Silverstruk Oct 01 '12 at 00:35

4 Answers4

9

Using Linq and tuples:

var arr = new[] { 1, 2, 3, 4, 5, 6 };

arr.SelectMany((fst, i) => arr.Skip(i + 1).Select(snd => (fst, snd)));
danplisetsky
  • 211
  • 2
  • 4
7

If you like Linq:

var ar = new int[] {1, 2, 3, 4, 5};

var combo = (from left in ar
            from right in ar where right > left 
            select new { left, right }).ToArray();
Spevy
  • 1,325
  • 9
  • 22
  • 2
    Well done for going with LINQ. I don't understand why so many of the other answers here are using `for`/`foreach` loops - they are simply more difficult to follow. LINQ is much clearer and easier to maintain. +1 – Enigmativity Oct 01 '12 at 00:44
  • Maybe people feel it's better to provide a solution that can be retrofitted to more .NET versions (since LINQ is a recent addition), or can be more easily converted to other languages? – Daniel Becroft Oct 01 '12 at 01:53
2

For the data from your sample you can do it with a trivial pair of nested loops:

var list = new List<int>{1,2,3,4,5,6};
var res = new List<int>();
for (int i = 0 ; i != list.Count ; i++) {
    for (int j = i+1 ; j != list.Count ; j++) {
        res.Add(list[i]*10+list[j]);
    }
}

For more complex data, you can use a string concatenation trick:

var list = new List<int>{98,76,54,32,10};
var res = new List<int>();
for (int i = 0 ; i != list.Count ; i++) {
    for (int j = i+1 ; j != list.Count ; j++) {
        res.Add(int.Parse(string.Format("{0}{1}", list[i], list[j])));
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1
var newList = new List<int>();
foreach(var i in originalList)
    for(int j = i + 1; j < originalList.Count; ++j)
        newList.Add(originalList[i] * 10 + originalList[j]);

Should help...

Sidharth Mudgal
  • 4,234
  • 19
  • 25