stefan1919

Subset Sums

Sep 12th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApplication6
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int n = int.Parse(Console.ReadLine());
  14.             int[] numbers = Console.ReadLine().Split().Select(int.Parse).Distinct().ToArray();
  15.  
  16.             var subset = new List<int>();
  17.             double combinations = Math.Pow(2, numbers.Length);
  18.  
  19.             bool isEqual = false;
  20.  
  21.             for (int i = 0; i < combinations; i++)//these are all of the possible combinations between numbers in the set, also called subset
  22.             {
  23.                 int sum = 0; // here we save the value of the current sum
  24.                 for (int j = 0; j < numbers.Length; j++)// here we have all indexes if the numbers in the set
  25.                 {
  26.                     int mask = i & (1 << j); // Mask is extremely important. If the value of the mask is 001 we take only the first number, if the value is 101 we take the first and the third number etc.
  27.                     if (mask != 0)
  28.                     {
  29.                         sum += numbers[0 + j];
  30.                         subset.Add(numbers[0 + j]);
  31.                     }
  32.                 }
  33.  
  34.                 if (sum == n)
  35.                 {
  36.                     Console.WriteLine(string.Join(" + ", subset) + " = " + sum);
  37.                     isEqual = true;
  38.                 }
  39.  
  40.                 subset.Clear();
  41.             }
  42.  
  43.             if (!isEqual)
  44.             {
  45.                 Console.WriteLine("No matching subsets.");
  46.             }
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment