Advertisement
sashomaga

Variations of K elements from the set N

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