Advertisement
stanevplamen

02.01.17.SubsetSumExactElements

Jul 2nd, 2013
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class SubsetSums
  5. {
  6.     static void Main()
  7.     {
  8.         Console.Write("Please enter the subset sum to check S = ");
  9.         int checkedSum = int.Parse(Console.ReadLine());
  10.         Console.Write("Please enter the lenght of the array N = ");
  11.         int arrayLenght = int.Parse(Console.ReadLine());
  12.         Console.Write("Please enter the number of summed elements to check K = ");
  13.         int k = int.Parse(Console.ReadLine());
  14.         long[] nArray = new long[arrayLenght];
  15.         Console.WriteLine("Please enter the elements on separate rows");
  16.         for (int i = 0; i < arrayLenght; i++)
  17.         {
  18.             nArray[i] = long.Parse(Console.ReadLine());
  19.         }
  20.  
  21.         int counter = 0;
  22.         int counterTwo = 0;
  23.         long currentSum = 0;
  24.         List<long> intList = new List<long>();
  25.         long iterationsNumber = (long)Math.Pow((double)2, nArray.Length);
  26.  
  27.         Console.WriteLine("The {1} elements which sum is equal to the requested sum ({0}) are: ", checkedSum, k);
  28.         for (int i = 1; i <= (iterationsNumber - 1); i++)
  29.         {
  30.             counterTwo = 0;
  31.             currentSum = 0;
  32.             for (int j = 0; j < nArray.Length; j++)
  33.             {
  34.                 long mask = 1 << j;
  35.                 long nAndMask = mask & i;
  36.                 long bit = nAndMask >> j;
  37.  
  38.                 if (bit == 1)
  39.                 {
  40.                     currentSum = currentSum + nArray[j];
  41.                     intList.Add(nArray[j]);
  42.                     counterTwo++;
  43.                 }
  44.             }
  45.             if (currentSum == checkedSum && counterTwo == k)
  46.             {
  47.                 foreach (int c in intList)
  48.                 {
  49.                     Console.Write("{0},", c);
  50.                 }
  51.                 Console.Write("\b;");
  52.                 Console.WriteLine();
  53.                 counter++;
  54.                 intList = new List<long>();
  55.             }
  56.             else
  57.             {
  58.                 intList = new List<long>();
  59.             }
  60.         }
  61.         if (counter == 0)
  62.         {
  63.             Console.WriteLine("There are no {0} elements which have sum {1}", k, checkedSum);
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement