Advent of Code - Day 10
Mix.install(
[
{:kino_aoc, git: "https://github.com/ljgago/kino_aoc"}
],
force: true
)
Section
{:ok, puzzle_input} = KinoAOC.download_puzzle("2022", "10", System.fetch_env!("LB_SESSION"))
input = """
addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop
"""
instructions =
puzzle_input
|> String.split("\n", trim: true)
defmodule Register do
def read(instructions, register \\ [1])
def read([], register), do: Enum.reverse(register)
def read(["noop" | instructions], register), do: read(instructions, [hd(register) | register])
def read(["addx " <> str_value | instructions], register) do
value = String.to_integer(str_value)
previous_state = hd(register)
read(instructions, [previous_state + value | [previous_state | register]])
end
# Part 1
def signal_strength(register) do
register
|> Enum.with_index()
|> Enum.slice(19..length(register)//40)
|> Enum.map(fn {x, i} -> x * (i + 1) end)
|> Enum.sum()
end
# Part2
def draw(register) do
register
|> Stream.chunk_every(40)
|> Stream.map(fn line ->
line
|> Enum.with_index()
|> Enum.map(&draw_sprite/1)
|> to_string()
end)
|> Enum.map(&IO.puts/1)
end
def draw_sprite({r_value, position}) when position in [r_value - 1, r_value, r_value + 1],
do: "#"
def draw_sprite({_r_value, _position}), do: " "
end
Part 1
instructions
|> Register.read()
|> Register.signal_strength()
Part 2
instructions
|> Register.read()
|> Register.draw()