Day 10
Section
noop
addx 3
addx -5
yields
1 2 3 4 5 6
[1, 1, 1, 1, 4, 4, -1]
defmodule Day10 do
def part1(input) do
[20, 60, 100, 140, 180, 220]
|> Enum.map(&(&1 * input[&1]))
|> Enum.sum()
end
def part2(input) do
1..241
|> Enum.chunk_every(40, 40, :discard)
|> Enum.each(fn chunk ->
chunk
|> Enum.map(fn cycle ->
pos = rem(cycle, 40) - 1
if abs(pos - input[cycle]) <= 1 do
IO.ANSI.format([:blue_background, :blue, "%"], true)
else
IO.ANSI.format([:red_background, :red, " "], true)
end
end)
|> IO.puts()
end)
end
def parse_input(path) do
path
|> File.stream!()
|> Stream.map(&String.trim/1)
|> Enum.flat_map(fn
"addx " <> s -> [0, String.to_integer(s)]
"noop" -> [0]
end)
|> to_prefix_sum([1, 1])
|> Enum.with_index()
|> Map.new(fn {s, i} -> {i, s} end)
end
defp to_prefix_sum([h | t], acc), do: to_prefix_sum(t, [h + hd(acc) | acc])
defp to_prefix_sum([], acc), do: Enum.reverse(acc)
end
input = Day10.parse_input("#{__DIR__}/day10.txt")
Day10.part1(input)
Day10.part2(input)