2

I am stuck with this problem of trying to generate all the variations of K elements from the set [1..N]. I also had an idea that I can do that with k levels of nested loops and tried to do that recursively, but without success.


I have this function:

public static void PrintVariation(int n, int k, int[] array) 
{ 
   //when k = 2 

   for (int i = 0; i < n; i++) 
   { 
      for (int j = 0; j < n; j++) 
      { 
         Console.WriteLine("{0}, {1}", array[i], array[j]); 
      } 
   } 
} 

But what am I supposed to do when k has a random value?

janw
  • 8,758
  • 11
  • 40
  • 62
user1127964
  • 21
  • 1
  • 2
  • The same problem in [python](http://stackoverflow.com/questions/8683092/calculating-combinations-of-length-k-from-a-list-of-length-n-using-recursion). – Daniel Fischer Jan 03 '12 at 14:26
  • You can read some interesting ideas here: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n – zmbq Jan 03 '12 at 14:44
  • For any K, *recursion* comes handy, instead of nesting loops in a non-recursive function. See my answer and try to use that recursively. – JOG Jan 04 '12 at 13:44

3 Answers3

0

Here is my hint: I think you are on the right track using recursion.

private List<Element[]> getVariations(int k, Element[] elements)
{
    // ... ^_^
    // use getVariations with less elements in here
}
JOG
  • 5,590
  • 7
  • 34
  • 54
0

I'm not sure I follow you though, but this is what I think you should do:

  1. Create a function that will 'generate a variation of K elements from the set [1..N]' It should return that variation.
  2. Call that function in a for-loop in another method that would add it to a generic collection. You may add another routine that would check if the variation generated by the function already exists in the collection and skip adding that variation to the collection.
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
  • i have this function: public static void PrintVariation(int n, int k, int[] array) { //when k = 2 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { Console.WriteLine("{0}, {1}", array[i], array[j]); } } } but what i suppose to do when k has a random value ?? – user1127964 Jan 03 '12 at 15:15
-1
public static List<List<T>> GetVariations<T>(int k, List<T> elements)
{
    List<List<T>> result = new List<List<T>>();
    if (k == 1)
    {
        result.AddRange(elements.Select(element => new List<T>() { element }));
    }
    else
    {
        foreach (T element in elements)
        {
            List<T> subelements = elements.Where(e => !e.Equals(element)).ToList();
            List<List<T>> subvariations = GetVariations(k - 1, subelements);
            foreach (List<T> subvariation in subvariations)
            {
                subvariation.Add(element);
                result.Add(subvariation);
            }
        }
     }
     return result;
 }
Petr Behenský
  • 620
  • 1
  • 6
  • 17