-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathday_10.ex
More file actions
70 lines (56 loc) · 1.42 KB
/
day_10.ex
File metadata and controls
70 lines (56 loc) · 1.42 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
defmodule AdventOfCode.Y2022.Day10 do
@moduledoc """
--- Day 10: Cathode-Ray Tube ---
Problem Link: https://adventofcode.com/2022/day/10
Difficulty: m
Tags: op-code visual-result
"""
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2022, 10)
def run(input \\ input()) do
cycles = simulate(parse(input))
part1 =
[20, 60, 100, 140, 180, 220]
|> Enum.map(fn c -> c * cycles[c] end)
|> Enum.sum()
part2 = draw(cycles)
{part1, part2}
end
defp parse(input) do
input
|> Transformers.lines()
|> Enum.map(fn
"noop" -> :noop
"addx " <> val -> {:addx, String.to_integer(val)}
end)
end
defp simulate(instructions) do
{cycles, _, _} =
Enum.reduce(instructions, {%{}, 1, 1}, fn
:noop, {acc, cycle, x} ->
{Map.put(acc, cycle, x), cycle + 1, x}
{:addx, v}, {acc, cycle, x} ->
acc = acc |> Map.put(cycle, x) |> Map.put(cycle + 1, x)
{acc, cycle + 2, x + v}
end)
cycles
end
defp draw(cycles) do
# credo:disable-for-next-line
IO.puts("")
for r <- 0..5 do
for c <- 0..39 do
cycle = r * 40 + c + 1
x = cycles[cycle]
if c in (x - 1)..(x + 1) do
IO.write("█")
else
IO.write("▒")
end
end
# credo:disable-for-next-line
IO.puts("")
end
:ok
end
end