Advertisement
Klaxon

[C# Arrays] Variations From Set

Sep 30th, 2013
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 KB | None | 0 0
  1. // 20. Write a program that reads two numbers N and K and generates all the variations of K elements from the set [1..N].
  2. // Example: N = 3, K = 2 -> {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}
  3.  
  4. using System;
  5.  
  6. class VariationsFromSet
  7. {
  8.     // Calculate variations
  9.     private static void Variations(int[] array, int k, int n)
  10.     {
  11.         if (array.Length == k)
  12.         {
  13.             Print(array);
  14.         }
  15.         else
  16.         {
  17.             for (int i = 1; i < n; i++)
  18.             {
  19.                 array[k] = i;
  20.                 Variations(array, k + 1, n);
  21.             }
  22.         }
  23.     }
  24.  
  25.     // Print the variations
  26.     private static void Print(int[] array)
  27.     {
  28.         Console.Write("{");
  29.         for (int i = 0; i < array.Length; i++)
  30.         {
  31.             if (i == array.Length - 1)
  32.             {
  33.                 Console.Write("{0}", array[i]);
  34.                 Console.Write("} ");
  35.             }
  36.             else
  37.             {
  38.                 Console.Write("{0}, ", array[i]);
  39.             }
  40.         }
  41.     }
  42.  
  43.     // Get N & K
  44.     static void Main()
  45.     {
  46.         Console.Write("Enter N: ");
  47.         int n = int.Parse(Console.ReadLine());
  48.         Console.Write("Enter K: ");
  49.         int k = int.Parse(Console.ReadLine());
  50.  
  51.         Console.WriteLine();
  52.         int[] var = new int[k];
  53.  
  54.         Variations(var, 0, n);
  55.         Console.WriteLine();
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement