Advertisement
sylviapsh

All Combinations Of K Elements In [1..N]

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