-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday05.ex
56 lines (48 loc) · 1.13 KB
/
day05.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
defmodule Elixir2020.Day05 do
# Parse file into:
# [
# {"BFBFBBB", "RLL"},
# {"BFFBBBB", "RRR"},
# {"FFBBFBF", "LLL"},
# ...
# ]
def parse(filename) do
File.stream!(filename)
|> Enum.map(&String.trim/1)
|> Enum.map(fn s -> String.split_at(s, 7) end)
end
def get_row({bf_string, _lr_string}), do: decode_binary(bf_string, "B")
def get_column({_bf_string, lr_string}), do: decode_binary(lr_string, "R")
def get_id(pair), do: get_row(pair) * 8 + get_column(pair)
def decode_binary(input, high_char) do
input
|> String.graphemes()
|> Enum.reduce(0, fn x, acc ->
acc = acc * 2
if x == high_char do
acc + 1
else
acc
end
end)
end
def find_missing(set, to_check) do
if MapSet.member?(set, to_check) do
find_missing(set, to_check + 1)
else
to_check
end
end
def part1(filename) do
parse(filename)
|> Enum.max_by(&get_id/1)
|> get_id()
end
def part2(filename) do
all_ids =
parse(filename)
|> Enum.map(&get_id/1)
|> MapSet.new()
find_missing(all_ids, Enum.min(all_ids))
end
end