Advent of Code 2015 Day 17 Part 2
Mix.install([
{:kino_aoc, "~> 0.1"}
])
Get Inputs
{:ok, puzzle_input} =
KinoAOC.download_puzzle("2015", "17", System.fetch_env!("LB_SESSION"))
My answer
containers =
puzzle_input
|> String.split("\n")
|> Enum.map(&String.to_integer(&1))
|> Enum.sort(:desc)
defmodule Combinations do
def get(_, n) when n == 0, do: [[]]
def get([], _), do: []
def get([head | tail], n) do
with_head =
tail
|> get(n - 1)
|> Enum.map(fn combo -> [head | combo] end)
without_head = get(tail, n)
with_head ++ without_head
end
end
1..20
|> Enum.reduce_while(nil, fn length, _acc ->
num =
containers
|> Combinations.get(length)
|> Enum.count(fn combination -> Enum.sum(combination) == 150 end)
if num > 0 do
{:halt, num}
else
{:cont, nil}
end
end)