-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03.ex
48 lines (40 loc) · 1.3 KB
/
day03.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
defmodule Y2022.Day03 do
use Advent.Day, no: 03
def part1(input) do
input
|> Enum.map(fn string ->
halves = String.split_at(string, div(String.length(string), 2)) |> Tuple.to_list()
common_priority(halves).value
end)
|> Enum.sum()
end
def part2(input) do
input
|> Enum.chunk_every(3)
|> Enum.map(fn rucksacks -> common_priority(rucksacks).value end)
|> Enum.sum()
end
@doc """
iex> Day03.common_priority(["vJrwpWtwJgWr", "hcsFMMfFFhFp"])
%{item: "p", value: 16}
iex> Day03.common_priority(["jqHRNqRjqzjGDLGL", "rsFMfFZSrLrFZsSL"])
%{item: "L", value: 38}
"""
def common_priority(lists) do
common_item =
lists
|> Enum.map(&String.to_charlist/1)
|> common_elements()
|> hd()
# 38 is ?A - priority of "A" (27), 96 is ?a - priority of "a" (1)
value = if common_item in ?A..?Z, do: common_item - 38, else: common_item - 96
%{item: to_string([common_item]), value: value}
end
defp common_elements([a, b]), do: a -- a -- b
defp common_elements([a, b | rest]), do: common_elements([a, common_elements([b | rest])])
def parse_input(input) do
String.split(input, "\n", trim: true)
end
def part1_verify, do: input() |> parse_input() |> part1()
def part2_verify, do: input() |> parse_input() |> part2()
end