-3

I've tried looking and I didn't find much for what I'm trying to accomplish.

Lets say that I have a List<int> that has around 50 numbers

List<int> _myList = new List<int>();
for (int i = 0; i < 49; i++)
{
    _myList.Add(i);
}

How do I get a list of combinations based on an array for two?

For example my result set would look like

  1. 1,1
  2. 1,2
  3. 1,3
  4. 1,4
  5. 1,5

and those are considered unique. Is it possible to say 1,2 is the same as 2,1?

Dmitry
  • 13,797
  • 6
  • 32
  • 48
josh long
  • 3
  • 1
  • Do you want the result to contain only unique sets even if the list contains duplicate values? Or: Do you know that the list never contains duplicates? – olydis Aug 30 '15 at 20:13
  • @olydis If you're referring to my source list, the source list will never have duplicates – josh long Aug 30 '15 at 20:14
  • http://stackoverflow.com/questions/7802822/all-possible-combinations-of-a-list-of-values-in-c-sharp – Sirwan Afifi Aug 30 '15 at 20:15
  • Use the excellent [Combinatorics](http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G) library by Adrian Akison at CodeProject. Specifically, you would be using the **Combinations with Repetition** option. I've personally used this library for many different types of projects. – Idle_Mind Aug 30 '15 at 20:33

3 Answers3

1
var sets;

for (int i = 0; i < 49; i++)
{
   for (int j = 1; j < 49; j++)
   {
      if(setc.Contains(new Pair(_myList(i), _myList(j))==false)
      {
         sets.Add(new Pair(_myList(i), _myList(j))
      }
   }
}
Janusz Nowak
  • 2,595
  • 1
  • 17
  • 36
1

I'll assume that your source list is called input:

var output = new List<HashSet<int>>();
for (int i = 0; i < input.Count; i++)
    for (int j = i + 1; j < input.Count; j++)
        output.Add(new HashSet<int> { input[i], input[j] });

In case you want to actually output the result to the console:

foreach (var result in output)
    Console.WriteLine(string.Join(", ", result));
olydis
  • 3,192
  • 13
  • 28
  • for (int i = 0; i < output.Count; i++) { Console.WriteLine(output[i]); } i'm guessing this is not how you write it – josh long Aug 30 '15 at 20:24
  • Try `Console.WriteLine(string.Join(", ", output[i]));` instead (the loop is fine, of course...) – olydis Aug 30 '15 at 20:27
  • I hate to open another question but if I have two of the hashsets above that you created how can I get the same combinations of those two sets? – josh long Aug 30 '15 at 20:30
0

If you simply need total combinations then there is a formula

totalCombination = n!/(k! * (n-k)!)

if n=50 and k=2 then

we can resolve it as 50!/2!*48!

However to solve it programatically

for(int i=0;i<49;i++)
{
    for(int j=i+1;j<=49;j++)
    {
        //Collect all the combinations in the form of 'i, j'
    }
}
Lali
  • 2,816
  • 4
  • 30
  • 47