Advertisement
sylviapsh

NumsN&K to generate all variations of K elements in 1 To N

Jan 15th, 2013
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. using System;
  2.  
  3. class AllVariationsOfKElementsIn1ToN
  4. {
  5.   static void Main()
  6.   {
  7.     //Write a program that reads two numbers N and K and generates all the variations of K elements from the set [1..N]. Example:
  8.       //N = 3, K = 2 ->{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}
  9.     int numN = 3,
  10.         numK = 2;
  11.     int[] arrayOfNumbers = new int [numK]; //Create the array with the K variations dimention
  12.  
  13.     Variations(arrayOfNumbers, 0, numN); //Use the recursive algorithm for all the numbers N
  14.   }
  15.  
  16.   static void Variations(int[] currentArray, int index, int numN)
  17.   {
  18.     if (index == currentArray.Length) //Bottom of recursion
  19.     {
  20.       for (int i = 0; i < currentArray.Length; i++) //Print the resulting variation
  21.       {
  22.         Console.Write("{0} ", currentArray[i]);
  23.       }
  24.       Console.WriteLine();
  25.     }
  26.     else
  27.     {
  28.       for (int j = 1; j <= numN; j++)//If we are still in the recursion. Take k elements and give their variation
  29.       {
  30.         currentArray[index] = j;
  31.         Variations(currentArray, index + 1, numN);
  32.       }
  33.     }
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement