Advertisement
sashomaga

Distinct combinations

Jan 9th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. //Write a program that reads two numbers N and K and generates all the combinations of K distinct elements from the set [1..N].
  5. //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}
  6. class Program
  7. {
  8.     static void Main()
  9.     {
  10.         Console.Write("Enter N: ");
  11.         int n = int.Parse(Console.ReadLine());
  12.         Console.Write("Enter K: ");
  13.         int k = int.Parse(Console.ReadLine());
  14.         int[] num = new int[k];
  15.         Generate(num, 1, k-1, n);
  16.     }
  17.  
  18.     private static void Generate(int[] num, int iteration, int index, int n)
  19.     {
  20.        
  21.         if (index == -1) // bottom of recursion
  22.         {
  23.             foreach (var item in num)
  24.             {
  25.                 Console.Write(item + " ");
  26.             }
  27.             Console.WriteLine();
  28.         }        
  29.         else
  30.         {
  31.             for (int i = iteration; i <= n; i++)
  32.             {
  33.                 num[index] = i;
  34.                 Generate(num, i + 1, index - 1, n); //recursion
  35.             }
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement