stefan1919

Sorted Subset Sums

Sep 12th, 2015
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 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 sum = int.Parse(Console.ReadLine());
  14.             int[] input = Console.ReadLine().Split(' ').Select(int.Parse).Distinct().ToArray();
  15.             List<List<int>> listToBeOrdered = new List<List<int>>();
  16.             double combinations = Math.Pow(2, input.Length);
  17.             bool thereAreElements = false;
  18.             for (int i = 1; i < combinations; i++)
  19.             {
  20.                 var subset = new List<int>();
  21.                 for (int bitPosition = 0; bitPosition < input.Length; bitPosition++)
  22.                 {
  23.                     if ((i & (1 << bitPosition)) != 0)
  24.                     {
  25.                         subset.Add(input[bitPosition]);
  26.                     }
  27.                 }
  28.                 if (subset.Sum() == sum)
  29.                 {
  30.                     listToBeOrdered.Add(subset);
  31.                     thereAreElements = true;
  32.                 }
  33.  
  34.                
  35.             }
  36.             if (!thereAreElements)
  37.             {
  38.                 Console.WriteLine("No matching subsets.");
  39.             }
  40.             else
  41.             {
  42.                 listToBeOrdered.ForEach(p => p.Sort());
  43.                 listToBeOrdered = listToBeOrdered.OrderBy(a => a.Count).ThenBy(b => b.First()).ToList();
  44.                 listToBeOrdered.ForEach(p => Console.WriteLine("{0} = {1}", string.Join(" + ", p), sum));
  45.             }
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment