summaryrefslogtreecommitdiff
path: root/2015/day17.exs
blob: 3bc52c31591a3acb50c6afdb4808b74a2dc2c581 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
containers =
  File.stream!("inputs/day17.txt")
  |> Stream.map(&String.trim/1)
  |> Stream.filter(&(&1 != ""))
  |> Enum.map(fn line ->
    {num, ""} = Integer.parse(line)
    num
  end)

defmodule EggnogStorage do
  use Agent

  def start do
    Agent.start_link(fn -> %{} end, name: __MODULE__)
  end

  def combinations(_containers, 0) do
    [[]]
  end

  def combinations([], _remainingCapacity) do
    []
  end

  def combinations(containers, remainingCapacity) do
    cached_value = Agent.get(__MODULE__, &Map.get(&1, {containers, remainingCapacity}))

    if cached_value do
      cached_value
    else
      [nextContainer | remainingContainers] = containers

      combinationsWithThisContainer =
        if nextContainer <= remainingCapacity do
          Enum.map(
            combinations(remainingContainers, remainingCapacity - nextContainer),
            fn x -> [nextContainer | x] end
          )
        else
          []
        end

      combinationsWithoutThisContainer = combinations(remainingContainers, remainingCapacity)

      result = combinationsWithThisContainer ++ combinationsWithoutThisContainer

      Agent.update(__MODULE__, &Map.put(&1, {containers, remainingCapacity}, result))
      result
    end
  end
end

{:ok, _} = EggnogStorage.start()

combinations = EggnogStorage.combinations(containers, 150)
IO.puts("Combinations: #{length(combinations)}")

frequencies = Enum.map(combinations, &length/1) |> Enum.frequencies()
dbg(frequencies)