Advertisement
sylviapsh

Subset Sums

Dec 27th, 2012
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. using System;
  2. class SubsetSums
  3. {
  4.   static void Main()
  5.   {
  6.     //Telerik Academy
  7.     //You are given a list of N numbers. Write a program that counts all non-empty subsets from this list, which have sum of their elements exactly S.
  8.     //Example: if you have a list with 4 elements: { 1, 2, 3, 4 } and you are searching the number of non-empty subsets which sum is 4, the answer will be 2. The subsets are: { 1, 3 } and { 4 }.
  9.  
  10.     long sumS = int.Parse(Console.ReadLine());
  11.     byte numN = byte.Parse(Console.ReadLine());
  12.     long[] numsArray = new long[numN];
  13.     int subsCounter = 0;
  14.  
  15.     for (byte counter = 0; counter < numN; counter++)
  16.     {
  17.       long inputNumber = long.Parse(Console.ReadLine());
  18.       numsArray[counter] = inputNumber;
  19.     }
  20.  
  21.     int combinations = (1 << numN) - 1; // number of the combinations of the numbers which is 2^N-1 (excluding 0)
  22.  
  23.     for (int i = 1; i <= combinations; i++) // go through each combination
  24.     {
  25.       long subsetSum = 0;
  26.       for (int j = 0; j < numN; j++) // checks each bit in i-th combination
  27.         if (((i >> j) & 1) == 1) subsetSum += numsArray[j]; // and if bit is set includes corresponding number into the subsetSum
  28.       if (subsetSum == sumS) subsCounter++; // each sum equal to sumS increases the subscounter
  29.     }
  30.  
  31.     Console.WriteLine(subsCounter);
  32.   }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement