-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_16.ex
58 lines (47 loc) · 2.06 KB
/
day_16.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
defmodule AdventOfCode.Y2021.Day16 do
@moduledoc """
--- Day 16: Packet Decoder ---
Problem Link: https://adventofcode.com/2021/day/16
Difficulty: m
Tags: bitwise
"""
alias AdventOfCode.Helpers.InputReader
def input, do: InputReader.read_from_file(2021, 16)
def run(input \\ input()) do
{input, _} = input |> Base.decode16!() |> parse_packet()
{sum(input), eval(input)}
end
defp parse_packet(<<ver::3, 4::3, rest::bitstring>>) do
{val, rest} = parse_literal(rest, 0)
{{:literal, ver, val}, rest}
end
defp parse_packet(<<ver::3, type::3, 0::1, length::15, rest::bitstring>>) do
<<subpackets::bitstring-size(length), rest::bitstring>> = rest
{{type, ver, parse_packets(subpackets)}, rest}
end
defp parse_packet(<<ver::3, type::3, 1::1, length::11, rest::bitstring>>) do
{val, rest} = Enum.map_reduce(1..length, rest, fn _, acc -> parse_packet(acc) end)
{{type, ver, val}, rest}
end
defp parse_packets({packet, <<>>}), do: packet |> List.wrap()
defp parse_packets({packet, rest}), do: [packet | parse_packets(rest)]
defp parse_packets(packet), do: parse_packets(parse_packet(packet))
defp parse_literal(<<1::1, bits::4, rest::bitstring>>, acc) do
parse_literal(rest, acc * 0x10 + bits)
end
defp parse_literal(<<0::1, bits::4, rest::bitstring>>, acc) do
{acc * 0x10 + bits, rest}
end
defp sum({:literal, ver, _}), do: ver
defp sum({_, ver, val}), do: Enum.reduce(val, ver, &(sum(&1) + &2))
defp eval({:literal, _, val}), do: val
defp eval({0, _, _} = packet), do: reduce(packet, 0, &+/2)
defp eval({1, _, _} = packet), do: reduce(packet, 1, &*/2)
defp eval({2, _, _} = packet), do: reduce(packet, :inf, &min/2)
defp eval({3, _, _} = packet), do: reduce(packet, 0, &max/2)
defp eval({5, _, _} = packet), do: compare(packet, &>/2)
defp eval({6, _, _} = packet), do: compare(packet, &</2)
defp eval({7, _, _} = packet), do: compare(packet, &==/2)
defp reduce({_, _, val}, x, f), do: Enum.reduce(val, x, &f.(eval(&1), &2))
defp compare({_, _, [a, b]}, f), do: (f.(eval(a), eval(b)) && 1) || 0
end