Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class AllVariationsOfKElementsIn1ToN
- {
- static void Main()
- {
- //Write a program that reads two numbers N and K and generates all the variations of K elements from the set [1..N]. Example:
- //N = 3, K = 2 ->{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}
- int numN = 3,
- numK = 2;
- int[] arrayOfNumbers = new int [numK]; //Create the array with the K variations dimention
- Variations(arrayOfNumbers, 0, numN); //Use the recursive algorithm for all the numbers N
- }
- static void Variations(int[] currentArray, int index, int numN)
- {
- if (index == currentArray.Length) //Bottom of recursion
- {
- for (int i = 0; i < currentArray.Length; i++) //Print the resulting variation
- {
- Console.Write("{0} ", currentArray[i]);
- }
- Console.WriteLine();
- }
- else
- {
- for (int j = 1; j <= numN; j++)//If we are still in the recursion. Take k elements and give their variation
- {
- currentArray[index] = j;
- Variations(currentArray, index + 1, numN);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement