AoC 2022 Day 10
Mix.install([:kino])
defmodule Utils do
def split(line, sep \\ "") do
String.split(line, sep, trim: true)
end
def split_all_lines(text, sep \\ "") do
text
|> String.split("\n", trim: true)
|> Enum.map(&split(&1, sep))
end
def to_numbers(number) when is_binary(number) do
String.to_integer(number)
end
def to_numbers(numbers) when is_list(numbers) do
Enum.map(numbers, &to_numbers/1)
end
def to_matrix(text, sep \\ "") do
text
|> split_all_lines(sep)
|> then(fn data ->
for {row, r} <- Enum.with_index(data), {col, c} <- Enum.with_index(row) do
{{r, c}, col}
end
end)
|> Map.new()
end
end
Setup
import Utils
input = Kino.Input.textarea("Input:")
text = Kino.Input.read(input)
data =
split_all_lines(text, " ")
|> Enum.map(fn
["noop"] -> :noop
["addx", n] -> {:addx, String.to_integer(n)}
end)
P1
defmodule P1 do
def solve(input) do
input
|> Enum.reduce({[], 1}, fn
:noop, {acc, s} -> {[[s] | acc], s}
{:addx, n}, {acc, s} -> {[[s, s] | acc], s + n}
end)
|> elem(0)
|> Enum.reverse()
|> List.flatten()
end
end
result = P1.solve(data)
Enum.map([20, 60, 100, 140, 180, 220], &(Enum.at(result, &1 - 1) * &1)) |> Enum.sum()
P2
for {s, i} <- Enum.with_index(result) do
if (s - rem(i, 40)) in [-1, 0, 1] do
"#"
else
" "
end
end
|> Enum.chunk_every(40)
|> Enum.each(&IO.puts/1)