AdventOfCode/2023/day4.exs

79 lines
1.9 KiB
Elixir
Raw Normal View History

2023-12-04 11:11:26 +00:00
#!/usr/bin/env elixir
2023-12-04 09:00:25 +00:00
defmodule Day4 do
def part1(input) do
input
2023-12-04 13:31:37 +00:00
|> Enum.map(fn 0 -> 0; num_winners -> 2 ** (num_winners - 1) end)
2023-12-04 09:00:25 +00:00
|> Enum.sum()
end
2023-12-04 11:11:26 +00:00
def part2(input) do
input
2023-12-04 13:31:37 +00:00
|> Enum.map(fn num_winners -> {_num_copies = 1, num_winners} end)
2023-12-04 11:11:26 +00:00
|> copy()
|> Enum.sum()
end
def copy([]), do: []
2023-12-04 13:31:37 +00:00
def copy([{num_copies, num_winners} | rest]) do
2023-12-04 11:11:26 +00:00
{to_copy, left_alone} = Enum.split(rest, num_winners)
copied =
2023-12-04 13:31:37 +00:00
Enum.map(to_copy, fn {child_num_copies, num_winners} ->
{num_copies + child_num_copies, num_winners}
2023-12-04 11:11:26 +00:00
end)
2023-12-04 13:31:37 +00:00
[num_copies | copy(copied ++ left_alone)]
2023-12-04 09:00:25 +00:00
end
def input do
with [input_filename] <- System.argv(),
{:ok, input} <- File.read(input_filename) do
input
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
2023-12-04 13:31:37 +00:00
[_card_id, winning, have] = String.split(line, [": ", " | "])
2023-12-04 09:00:25 +00:00
2023-12-04 13:31:37 +00:00
winning = winning |> String.split(" ", trim: true) |> MapSet.new()
have = have |> String.split(" ", trim: true) |> MapSet.new()
2023-12-04 09:00:25 +00:00
2023-12-04 13:31:37 +00:00
MapSet.intersection(winning, have) |> MapSet.size()
2023-12-04 09:00:25 +00:00
end)
else
_ -> :error
end
end
#######################
# HERE BE BOILERPLATE #
#######################
def run do
case input() do
:error -> print_usage()
input -> run_parts_with_timer(input)
end
end
defp run_parts_with_timer(input) do
run_with_timer(1, fn -> part1(input) end)
run_with_timer(2, fn -> part2(input) end)
end
defp run_with_timer(part, fun) do
{time, result} = :timer.tc(fun)
IO.puts("Part #{part} (completed in #{format_time(time)}):\n")
IO.puts("#{inspect(result)}\n")
end
defp format_time(μsec) when μsec < 1_000, do: "#{μsec}μs"
defp format_time(μsec) when μsec < 1_000_000, do: "#{μsec / 1000}ms"
defp format_time(μsec), do: "#{μsec / 1_000_000}s"
defp print_usage do
IO.puts("Usage: elixir day4.exs input_filename")
end
end
2023-12-04 11:11:26 +00:00
Day4.run()