-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_23.ex
97 lines (78 loc) · 2.52 KB
/
day_23.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
defmodule AdventOfCode.Y2015.Day23 do
@moduledoc """
--- Day 23: Opening the Turing Lock ---
Problem Link: https://adventofcode.com/2015/day/23
Difficulty: m
Tags: op-code emulation
"""
require Integer
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2015, 23)
def run(input \\ input()) do
input = parse(input)
size = Enum.count(input)
{
execute(input, %{a: 0, b: 0}, 1, size).b,
execute(input, %{a: 1, b: 0}, 1, size).b
}
end
defp execute(_, registers, idx, size) when idx > size, do: registers
defp execute(instructions, registers, idx, size) do
instruction = Map.fetch!(instructions, idx)
{next_idx, registers} = handle_instruction({idx, instruction}, registers)
execute(instructions, registers, next_idx, size)
end
def parse(data \\ input()) do
data
|> Transformers.lines()
|> Enum.map(fn line ->
~r/\s+|\,/
|> Regex.split(line, trim: true)
|> parse_instruction()
end)
|> Enum.with_index(1)
|> Map.new(fn {a, b} -> {b, a} end)
end
defp parse_instruction([instruction, register, value]) do
{
to_atom(instruction),
to_atom(register),
String.to_integer(value)
}
end
defp parse_instruction(["jmp", value]) do
{:jmp, String.to_integer(value)}
end
defp parse_instruction([instruction, register]) do
{
to_atom(instruction),
to_atom(register)
}
end
@tokens ~w/a b hlf tpl jmp inc jie jio/
defp to_atom(instruction) when instruction in @tokens do
String.to_atom(instruction)
end
defp handle_instruction({idx, {:inc, register}}, registers) do
{idx + 1, Map.update(registers, register, 1, &(&1 + 1))}
end
defp handle_instruction({idx, {:hlf, register}}, registers) do
{idx + 1, Map.update(registers, register, 0, &div(&1, 2))}
end
defp handle_instruction({idx, {:tpl, register}}, registers) do
{idx + 1, Map.update(registers, register, 0, &(3 * &1))}
end
defp handle_instruction({idx, {:jmp, value}}, registers) do
{idx + value, registers}
end
defp handle_instruction({idx, {:jio, register, value}}, registers) do
register_value = Map.fetch!(registers, register)
next_idx = (register_value == 1 && idx + value) || idx + 1
{next_idx, registers}
end
defp handle_instruction({idx, {:jie, register, value}}, registers) do
register_value = Map.fetch!(registers, register)
next_idx = (Integer.is_even(register_value) && idx + value) || idx + 1
{next_idx, registers}
end
end