-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday11.ex
76 lines (63 loc) · 2.12 KB
/
day11.ex
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
71
72
73
74
75
76
defmodule Y2019.Day11 do
use Advent.Day, no: 11
alias Y2019.Intcode
def part1(intcode) do
do_paint(intcode, {Map.new(), {0, 0}}, 0, :up)
|> map_size()
end
def part2(intcode) do
do_paint(intcode, {Map.new(), {0, 0}}, 1, :up)
|> visualize()
end
def visualize(canvas, func \\ &to_pixel/1) do
{{{min_x, _}, _}, {{max_x, _}, _}} = Enum.min_max_by(canvas, fn {{x, _}, _} -> x end)
{{{_, min_y}, _}, {{_, max_y}, _}} = Enum.min_max_by(canvas, fn {{_, y}, _} -> y end)
for y <- max_y..min_y, x <- min_x..max_x do
Map.get(canvas, {x, y}, 0)
end
|> Enum.chunk_every(max_x - min_x + 1)
|> Enum.each(&display(&1, func))
end
defp display(line, func) do
line
|> Enum.map(&func.(&1))
|> IO.puts()
end
defp to_pixel(1), do: "."
defp to_pixel(0), do: "X"
defp do_paint(intcode, {canvas, position}, input, dir) do
intcode =
intcode
|> Intcode.add_input(input)
|> Intcode.run()
case Intcode.status(intcode) do
:paused ->
{[color, turn_dir], intcode} = Intcode.pop_outputs(intcode)
# Update canvas and get new input
canvas = Map.put(canvas, position, color)
{new_position, new_dir} = turn_and_move(position, dir, turn_dir)
new_colour = Map.get(canvas, new_position, 0)
do_paint(intcode, {canvas, new_position}, new_colour, new_dir)
:halted ->
canvas
end
end
defp turn_and_move(pos, current_dir, turn_dir) do
new_dir = turn(current_dir, turn_dir)
{move(new_dir, pos), new_dir}
end
defp turn(:up, 0), do: :left
defp turn(:up, 1), do: :right
defp turn(:down, 0), do: :right
defp turn(:down, 1), do: :left
defp turn(:left, 0), do: :down
defp turn(:left, 1), do: :up
defp turn(:right, 0), do: :up
defp turn(:right, 1), do: :down
defp move(:up, {x, y}), do: {x, y + 1}
defp move(:left, {x, y}), do: {x - 1, y}
defp move(:down, {x, y}), do: {x, y - 1}
defp move(:right, {x, y}), do: {x + 1, y}
def part1_verify, do: input() |> Intcode.from_string() |> Intcode.new() |> part1()
def part2_verify, do: input() |> Intcode.from_string() |> Intcode.new() |> part2()
end