2020-12-16 09:11:24 +00:00
|
|
|
defmodule Day16Part1 do
|
|
|
|
def run do
|
2020-12-16 14:57:57 +00:00
|
|
|
{rules, tickets} = File.read!("input") |> parse_input()
|
2020-12-16 09:11:24 +00:00
|
|
|
|
2020-12-16 14:57:57 +00:00
|
|
|
Enum.flat_map(tickets, &find_invalid_fields(&1, rules))
|
2020-12-16 09:11:24 +00:00
|
|
|
|> Enum.sum()
|
|
|
|
|> IO.puts()
|
|
|
|
end
|
|
|
|
|
2020-12-16 14:57:57 +00:00
|
|
|
def find_invalid_fields(ticket, rules) do
|
|
|
|
Enum.reject(ticket, fn field ->
|
|
|
|
Enum.any?(rules, fn {_name, range1, range2} -> field in range1 || field in range2 end)
|
|
|
|
end)
|
|
|
|
end
|
|
|
|
|
2020-12-16 09:11:24 +00:00
|
|
|
def parse_input(input) do
|
2020-12-16 14:57:57 +00:00
|
|
|
[rules, _, [_ | nearby_tickets]] =
|
2020-12-16 09:11:24 +00:00
|
|
|
input
|
|
|
|
|> String.split("\n\n", trim: true)
|
|
|
|
|> Enum.map(&String.split(&1, "\n", trim: true))
|
|
|
|
|
|
|
|
rules = Enum.map(rules, &parse_rule/1)
|
|
|
|
|
2020-12-16 14:57:57 +00:00
|
|
|
nearby_tickets =
|
|
|
|
for ticket <- nearby_tickets do
|
|
|
|
ticket |> String.split(",") |> Enum.map(&String.to_integer/1)
|
|
|
|
end
|
2020-12-16 09:11:24 +00:00
|
|
|
|
2020-12-16 14:57:57 +00:00
|
|
|
{rules, nearby_tickets}
|
2020-12-16 09:11:24 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def parse_rule(rule) do
|
|
|
|
[name | ranges] =
|
|
|
|
Regex.run(~r/\A(.*): (\d+)-(\d+) or (\d+)-(\d+)\z/, rule, capture: :all_but_first)
|
|
|
|
|
|
|
|
[a, b, c, d] = Enum.map(ranges, &String.to_integer/1)
|
|
|
|
{name, a..b, c..d}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
Day16Part1.run()
|