Created
December 17, 2015 14:25
-
-
Save johnboker/e1c4d58ad5d441e51461 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace AdventOfCodeDay17 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var input = new[] { 50, 44, 11, 49, 42, 46, 18, 32, 26, 40, 21, 7, 18, 43, 10, 47, 36, 24, 22, 40 }; | |
var subsets = input.ToList().Subsets().Where(a => a.Sum() == 150); | |
var min = subsets.Min(a => a.Count(b => b != 0)); | |
var part2 = subsets.Where(a => a.Count(b => b != 0) == min).Count(); | |
Console.WriteLine($"Number of combinations: {subsets.Count()}"); | |
Console.WriteLine($"Number of combinations: {part2}"); | |
Console.ReadLine(); | |
} | |
} | |
public static class Extensions | |
{ | |
public static IEnumerable<IEnumerable<T>> Subsets<T>(this IList<T> set) | |
{ | |
var state = new BitArray(set.Count); | |
do | |
{ | |
yield return Enumerable.Range(0, state.Count).Select(i => state[i] ? set[i] : default(T)); | |
} | |
while (Increment(state)); | |
} | |
public static bool Increment(BitArray flags) | |
{ | |
int x = flags.Count - 1; | |
while (x >= 0 && flags[x]) flags[x--] = false; | |
if (x >= 0) flags[x] = true; | |
return x >= 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment