SHARE
TWEET

Arrays.21.Combinations.cs

Teodor92 Jan 22nd, 2013 187 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. class Combinations
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("Enter the number of elements:");
  8.         long numberOfElements = long.Parse(Console.ReadLine());
  9.         Console.WriteLine("Enter K:");
  10.         long K = long.Parse(Console.ReadLine());
  11.         long[] elements = new long[numberOfElements];
  12.         string subset = "";
  13.         int lenCounter = 0;
  14.         for (int i = 0; i < elements.Length; i++)
  15.         {
  16.             Console.WriteLine("Enter element № {0}", i + 1);
  17.             elements[i] = long.Parse(Console.ReadLine());
  18.         }
  19.         int maxSubsets = (int)Math.Pow(2, numberOfElements);
  20.         for (int i = 1; i < maxSubsets; i++)
  21.         {
  22.             subset = "";
  23.             for (int j = 0; j <= numberOfElements; j++)
  24.             {
  25.                 int mask = 1 << j;
  26.                 int nAndMask = i & mask;
  27.                 int bit = nAndMask >> j;
  28.                 if (bit == 1)
  29.                 {
  30.                     subset = subset + " " + elements[j];
  31.                     lenCounter++;
  32.                 }
  33.             }
  34.             if (lenCounter == K)
  35.             {
  36.                 Console.WriteLine(subset);  
  37.             }
  38.             lenCounter = 0;
  39.         }
  40.     }
  41. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top