Advertisement
stefkay

07.SortedSubsetSums

Sep 4th, 2015
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class SortSubsetSums
  6. {
  7.     static void Main()
  8.     {
  9.         int n = int.Parse(Console.ReadLine());
  10.         List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).Distinct().ToList();
  11.  
  12.         int subsetsNumber = 1 << numbers.Count;
  13.  
  14.         List<List<int>> allSets = new List<List<int>>();
  15.         List<int> singleSubset = new List<int>();
  16.         List<List<int>> sortedByCount = new List<List<int>>();
  17.  
  18.         allSets = CreateSubsets(subsetsNumber, numbers, allSets, singleSubset);
  19.        
  20.         foreach (List<int> l in allSets.Where(x => x.Sum() == n && x.Count > 0))
  21.         {
  22.             sortedByCount.Add(l);
  23.         }
  24.  
  25.         if (sortedByCount.Count == 0)
  26.         {
  27.             Console.WriteLine("No matching subsets.");
  28.         }
  29.         else
  30.         {
  31.             PrintSums(sortedByCount, n);
  32.         }
  33.     }
  34.  
  35.     static List<List<int>> CreateSubsets(int subsetsNumber, List<int> numbers, List<List<int>> allSets, List<int> singleSubset)
  36.     {
  37.         for (int i = 0; i < subsetsNumber; i++)
  38.         {
  39.             int pos = numbers.Count - 1;
  40.             int bitmask = i;
  41.  
  42.             while (bitmask > 0)
  43.             {
  44.                 if ((bitmask & 1) == 1)
  45.                 {
  46.                     singleSubset.Add(numbers[pos]);
  47.                 }
  48.                 bitmask >>= 1;
  49.                 pos--;
  50.             }
  51.             singleSubset.Sort();
  52.             allSets.Add(new List<int>(singleSubset));
  53.             singleSubset.Clear();
  54.         }
  55.         return allSets;
  56.     }
  57.  
  58.     static void PrintSums(List<List<int>> uniqueElements, int n)
  59.     {
  60.         IEnumerable<List<int>> query = uniqueElements.OrderBy(l => l.Count).ThenBy(l => l[0]);
  61.  
  62.         foreach (List<int> list in query)
  63.         {
  64.             foreach (int num in list)
  65.             {
  66.                 if (list.IndexOf(num) < list.Count - 1)
  67.                 {
  68.                     Console.Write(num + " + ");
  69.                 }
  70.                 else
  71.                 {
  72.                     Console.Write(num);
  73.                 }
  74.             }
  75.             Console.WriteLine(" = {0}", n);
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement