AdventOfCode/day7/day7part2.exs

40 lines
981 B
Elixir
Raw Normal View History

2020-12-07 06:29:07 +00:00
defmodule Day7Part2 do
@bag_spec ~r/\A(\d) (\w+ \w+).*\z/
def run do
File.read!("input")
|> input_to_tree()
2020-12-07 09:42:38 +00:00
|> count_descendants("shiny gold")
2020-12-07 06:29:07 +00:00
|> IO.puts()
end
2020-12-07 09:42:38 +00:00
def count_descendants(tree, name) do
2020-12-07 06:29:07 +00:00
Enum.reduce(tree[name], 0, fn {size, child_name}, count ->
2020-12-07 09:42:38 +00:00
count + size + size * count_descendants(tree, child_name)
2020-12-07 06:29:07 +00:00
end)
end
def input_to_tree(input) do
input
2020-12-07 13:36:40 +00:00
|> String.split(".\n", trim: true)
2020-12-07 06:29:07 +00:00
|> Enum.map(&String.split(&1, " bags contain "))
|> Map.new(fn [parent, child_spec] -> {parent, parse_children(child_spec)} end)
end
def parse_children(child_spec) when is_binary(child_spec) do
child_spec
|> String.split(", ")
|> parse_children()
end
def parse_children(["no other bags"]), do: []
def parse_children(list) do
list
|> Enum.map(&Regex.run(@bag_spec, &1, capture: :all_but_first))
|> Enum.map(fn [count, type] -> {String.to_integer(count), type} end)
end
end
Day7Part2.run()