Watch
1
0
Fork
You've already forked advent-of-code
0

Day 16 Part 2

This commit is contained in:
Jeremy Kaplan 2020-12-16 00:04:37 -08:00
commit acbd4a0237

View file

@ -6,18 +6,17 @@ defmodule Day16 do
defp test_input do defp test_input do
""" """
class: 1-3 or 5-7 class: 0-1 or 4-19
row: 6-11 or 33-44 row: 0-5 or 8-19
seat: 13-40 or 45-50 seat: 0-13 or 16-19
your ticket: your ticket:
7,1,14 11,12,13
nearby tickets: nearby tickets:
7,3,47 3,9,18
40,4,50 15,1,5
55,2,20 5,14,9
38,6,12
""" """
end end
@ -80,6 +79,68 @@ defmodule Day16 do
Enum.map(nearby, &validate(fields, &1)) Enum.map(nearby, &validate(fields, &1))
|> Enum.sum() |> Enum.sum()
end end
def part2 do
{fields, mine, nearby} = read_input() |> parse_input()
Enum.filter(nearby, &(validate(fields, &1) == 0))
|> columns(Enum.count(fields))
|> deduce(fields)
|> departure(mine)
end
defp departure(mapping, ticket) do
Enum.reduce(mapping, 1, fn {name, idx}, product ->
if String.starts_with?(name, "departure") do
product * Enum.at(ticket, idx)
else
product
end
end)
end
defp columns(tickets, field_count) do
Enum.reduce(tickets, List.duplicate([], field_count), fn ticket, columns ->
Enum.zip(ticket, columns)
|> Enum.map(fn {value, list} -> [value | list] end)
end)
end
defp deduce(columns, fields) do
possible =
Enum.map(columns, fn values ->
Enum.filter(fields, fn field ->
Enum.all?(values, &can_match?(field, &1))
end)
end)
constrain(%{}, Enum.with_index(possible))
end
defp constrain(known, []), do: known
defp constrain(known, possible) do
{solved, unsolved} =
Enum.split_with(possible, fn {fields, _idx} ->
Enum.count(fields) == 1
end)
solved_names = Enum.map(solved, fn {[{name, _r1, _r2}], _idx} -> name end) |> MapSet.new()
new_possible =
Enum.map(unsolved, fn {fields, idx} ->
new_fields =
Enum.reject(fields, fn {name, _, _} ->
MapSet.member?(solved_names, name)
end)
{new_fields, idx}
end)
new_known = Enum.into(solved, known, fn {[{name, _r1, _r2}], idx} -> {name, idx} end)
constrain(new_known, new_possible)
end
end end
Day16.part1() |> IO.inspect() Day16.part1() |> IO.inspect()
Day16.part2() |> IO.inspect()