Day 2
This commit is contained in:
@@ -1,4 +1,15 @@
|
||||
defmodule Aoc2023.Common do
|
||||
def stringify(s) when is_binary(s) do s end
|
||||
def stringify(n) when is_integer(n) do inspect(n) end
|
||||
def stringify(nil), do: "nil"
|
||||
|
||||
def map_nth(tup, n, fun) do
|
||||
put_elem(tup, n, fun.(elem(tup, n)))
|
||||
end
|
||||
|
||||
defmacro pipe(expr) do
|
||||
quote do
|
||||
fn (val) -> val |> unquote(expr) end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
52
lib/day2.ex
Normal file
52
lib/day2.ex
Normal file
@@ -0,0 +1,52 @@
|
||||
defmodule Aoc2023.Day2 do
|
||||
use Aoc2023
|
||||
|
||||
def parse(input) do
|
||||
input
|
||||
|> String.split("\n")
|
||||
|> Enum.map(pipe(
|
||||
String.split(": ")
|
||||
|> then(fn ["Game " <> id, rounds] ->
|
||||
{String.to_integer(id),
|
||||
rounds
|
||||
|> String.split("; ")
|
||||
|> Enum.map(pipe(
|
||||
String.split(", ")
|
||||
|> Enum.map(pipe(
|
||||
String.split(" ")
|
||||
|> then(fn [n, color] ->
|
||||
{String.to_existing_atom(color), String.to_integer(n)}
|
||||
end)
|
||||
))
|
||||
))}
|
||||
end)
|
||||
))
|
||||
|> Enum.into(%{})
|
||||
end
|
||||
|
||||
@part1_available [
|
||||
red: 12, green: 13, blue: 14
|
||||
]
|
||||
def part1(input) do
|
||||
input
|
||||
|> Enum.filter(pipe(
|
||||
elem(1)
|
||||
|> Enum.all?(pipe(
|
||||
Enum.all?(fn {color, num} -> Keyword.get(@part1_available, color, 0) >= num end)
|
||||
))
|
||||
))
|
||||
|> Enum.map(pipe(elem(0)))
|
||||
|> Enum.sum
|
||||
end
|
||||
|
||||
def part2(input) do
|
||||
input
|
||||
|> Enum.map(pipe(
|
||||
elem(1)
|
||||
|> Enum.reduce(&(Keyword.merge(&1, &2, fn _, m1, m2 -> max(m1, m2) end)))
|
||||
|> Enum.map(pipe(elem(1)))
|
||||
|> Enum.product
|
||||
))
|
||||
|> Enum.sum
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user