Advertisement
nikolov_k

09 Sum of subsets

Dec 4th, 2012
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1. using System;
  2.  
  3. class SumOfSubset
  4. {
  5.     static int extractBit(int value,int position)
  6.     {
  7.         int mask = 1 << position;
  8.         int pAndMask = value & mask;
  9.         int bit = pAndMask >> position;
  10.         return bit;
  11.     }
  12.     static void Main()
  13.     {
  14.         Console.Write("N = ");
  15.         int n = int.Parse(Console.ReadLine());
  16.         int[] number = new int[n];
  17.         int allSubsets = 1;
  18.         int[] multiplier = new int[n];
  19.         int sum = 0;
  20.         string forPrint ="";
  21.         for (int i = 0; i < n; i++)
  22.         {
  23.             Console.Write("Number {0}: ", i+1);
  24.             number[i] = int.Parse(Console.ReadLine());
  25.             allSubsets *= 2;
  26.         }
  27.         for (int i = 1; i < allSubsets; i++)
  28.         {
  29.             for (int j = n-1; j >= 0; j--)
  30.             {
  31.                 multiplier[j] = extractBit(i, j);
  32.                 if (multiplier[j] == 1)
  33.                 {
  34.                     sum += number[j];
  35.                     forPrint += number[j].ToString() + " ";
  36.                 }
  37.             }
  38.             if (sum == 0)
  39.             {
  40.                 Console.WriteLine("Sum of numbers {0} is {1}",forPrint,sum);
  41.             }
  42.             sum = 0;
  43.             forPrint = "";
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement