Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class AllCombinationsOfKElementsIn1ToN
- {
- static void Main()
- {
- //Write a program that reads two numbers N and K and generates all the combinations of K distinct elements from the set [1..N]. Example:
- //N = 5, K = 2 -> {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5}
- int numN = 5,
- numK = 2;
- int[] arrayOfNumbers = new int[numK]; //Create the array with the K variations dimention
- Combinations(arrayOfNumbers, 0, numN,1);
- }
- static void Combinations(int[] currentArray, int index, int numN, int numK)
- {
- 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 = numK; j <= numN; j++)//If we are still in the recursion. Take k elements and give their combinations
- {
- currentArray[index] = j;
- Combinations(currentArray, index + 1, numN, j + 1);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement