Rucksack Reorganization
Mix.install([{:kino, "~> 0.7.0"}])
Input
input = Kino.Input.textarea("Input:")
Part 1
input = Kino.Input.read(input)
rucksacks =
input
|> String.trim()
|> String.split("\n")
|> Enum.map(fn s ->
len = String.length(s)
n = div(len, 2)
{String.slice(s, 0, n), String.slice(s, n, n)}
end)
priority = fn
[ch] when ch >= ?a and ch <= ?z -> 1 + ch - ?a
[ch] when ch >= ?A and ch <= ?Z -> ch - ?A + 1 + 26
end
Enum.map(rucksacks, fn {a, b} ->
a = MapSet.new(String.to_charlist(a))
b = MapSet.new(String.to_charlist(b))
MapSet.intersection(a, b) |> MapSet.to_list()
end)
|> Enum.map(priority)
|> Enum.sum()
Part 2
rucksacks =
input
|> String.trim()
|> String.split("\n")
|> Enum.chunk_every(3)
rucksacks
|> Enum.map(fn [a, b, c] ->
a = MapSet.new(String.to_charlist(a))
b = MapSet.new(String.to_charlist(b))
c = MapSet.new(String.to_charlist(c))
a
|> MapSet.intersection(b)
|> MapSet.intersection(c)
|> MapSet.to_list()
end)
|> Enum.map(priority)
|> Enum.sum()