Advertisement
kidroca

SortedSubsetSums

Sep 20th, 2015
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.63 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 Hmwrk_1_7
  8. {
  9.     internal class Program
  10.     {
  11.         private static void Main(string[] args)
  12.         {
  13.             int sum = int.Parse(Console.ReadLine());
  14.  
  15.             int[] input = Console.ReadLine().Split(' ').Select(int.Parse).Distinct().ToArray();
  16.  
  17.            // List<int> currentComb = new List<int>();
  18.             List<List<int>> allcombs = new List<List<int>>();
  19.  
  20.             double combinations = Math.Pow(2, input.Length);
  21.  
  22.             for (int mask = 0; mask < combinations; mask++)
  23.             {
  24.                 List<int> currentComb = new List<int>(); // Added
  25.  
  26.                 for (int i = 0; i < input.Length; i++)
  27.                 {
  28.                     if ((mask & (1 << i)) != 0)
  29.                     {
  30.                         currentComb.Add(input[i]);
  31.                     }
  32.                 }
  33.  
  34.                 if (currentComb.Sum() == sum)
  35.                 {
  36.                     currentComb.Sort(); // Added bonus
  37.                     allcombs.Add(currentComb);
  38.                 }
  39.  
  40.                // currentComb.Clear();
  41.  
  42.             }
  43.  
  44.  
  45.             if (allcombs.Count == 0)
  46.             {
  47.                 Console.WriteLine("No !");
  48.             }
  49.  
  50.             else
  51.             {
  52.  
  53.                 // allcombs.ForEach(list => list.Sort());
  54.                 allcombs = allcombs.OrderBy(a => a.Count).ThenBy(b => b.First()).ToList();
  55.  
  56.                 allcombs.ForEach(list => Console.WriteLine("{0} = {1}", string.Join(" + ", list), sum));
  57.  
  58.             }
  59.  
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement