Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am writing a bet settling app in C# and WinForms. I have 6 selections, 4 of them have won. I know that using the following formula from Excel:


This is coded into my app and working well: I can work out how many possible doubles (e.g., AB, AC, AD, AE, BC, BD, BE, etc.) need to be resolved.

But what I can't figure out is how to do the actual calculation. How can I efficiently code it so that every combination of A, B, C, and D has been calculated?

All my efforts thus far on paper have proved to be ugly and verbose: is there an elegant solution to this problem?

share|improve this question
This a general algorithmic problem and on-topic here. – user8 Nov 19 '11 at 10:44
does this blog post help at all? Generating a list of all the possible combinations lists of length n – Matt Ellen Nov 19 '11 at 12:50
up vote 1 down vote accepted

I don't speak C#, but here's the general idea in C-like pseudocode:

items = {A, B, C, D, E}
for (i = 0; i < items.count-1; i++)
    for (j = i+1; j < items.count; j++) {
        doSomethingWithPair(items[i], items[j])

In English, pick the first item and combine it with all the subsequent items. Then pick the next item and combine it with all subsequent items, and so on until you've combined the penultimate item with the ultimate item.

If order were important, i.e. you wanted permutations instead of combinations, pick both members of each pair from the full range of items. Change the outer loop so that it goes all the way to the end and the inner loop so that it starts from the beginning. Remember to check that i != j if you don't want permutations with replacement:

for (i = 0; i < items.count; i++) {
    for (j = 0; j < items.count; j++) {
        if (i == j) continue;        // avoid AA, BB, etc.
        doSomethingWithPair(items[i], items[j]);
share|improve this answer
+1 fine answer(If I interpreted the question correctly) – yati sagade Nov 19 '11 at 17:43
Just what I was looking for,many thanks. – sila Nov 21 '11 at 9:30

In LINQ you could do something like:

string[] items = new[] { "A", "B", "C", "D" };
var pairs = from firstIndex in Enumerable.Range(0, items.Length)
            from secondIndex in Enumerable.Range(firstIndex + 1, items.Length - firstIndex - 1)
            select new {First = items[firstIndex], Second = items[secondIndex]};
foreach(var pair in pairs)
    Console.WriteLine("{0},{1}", pair.First, pair.Second);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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