evgeni_tsn

Untitled

Sep 20th, 2015
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class SubsetSums
  6. {
  7.  
  8.     static void Main()
  9.     {
  10.         //int n = int.Parse(Console.ReadLine());
  11.         int n = 21;
  12.         //int[] numbers = Console.ReadLine().Split().Select(int.Parse).Distinct().ToArray();
  13.         int[] numbers = {2,3,4,5,12,32,15,12,1,4,2,3,5,6,1,22};
  14.  
  15.         var subset = new List<int>();
  16.         double combinations = Math.Pow(2, numbers.Length);
  17.  
  18.         bool isEqual = false;
  19.  
  20.         for (int i = 1; i < combinations; i++)
  21.         {
  22.             int sum = 0;
  23.             for (int j = 0; j < numbers.Length; j++)
  24.             {
  25.                 int mask = i & (1 << j);
  26.                 if (mask != 0)
  27.                 {
  28.                     sum += numbers[0 + j];
  29.                     subset.Add(numbers[0 + j]);
  30.                 }
  31.             }
  32.  
  33.             if (sum == n)
  34.             {
  35.                 Console.WriteLine(string.Join(" + ", subset) + " = " + sum);
  36.                 isEqual = true;
  37.             }
  38.  
  39.             subset.Clear();
  40.         }
  41.  
  42.         if (!isEqual)
  43.         {
  44.             Console.WriteLine("No matching subsets.");
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment