Skip to content

Commit 9aed672

Browse files
committed
day 12/2016
1 parent 9850d52 commit 9aed672

File tree

4 files changed

+72
-2
lines changed

4 files changed

+72
-2
lines changed

src/main/kotlin/me/grison/aoc/Strings.kt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,9 @@ fun String.subs(x: Int, y: Int) = substring(x, y)
133133

134134
operator fun String.get(x: Int, y: Int) = substring(x, y)
135135

136-
fun String.isAscii() = all { it.toInt() <= 255 }
136+
fun String.isAscii() = all { it.code <= 255 }
137+
138+
fun String.isDigits() = all { it.code in 48..57 }
137139

138140
fun String.split(at: Int) = listOf(this.take(at), this.drop(at))
139141

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package me.grison.aoc.y2016
2+
3+
import me.grison.aoc.Day
4+
import me.grison.aoc.isDigits
5+
import me.grison.aoc.words
6+
7+
class Day12 : Day(12, 2016) {
8+
override fun title() = "Leonardo's Monorail"
9+
10+
private val instructions = inputList.map { "$it ." }.map { it.words() }
11+
12+
override fun partOne() = emulate().getValue("a")
13+
14+
override fun partTwo() = emulate(c = 1).getValue("a")
15+
16+
private fun getValue(registers: Map<String, Int>, x: String) =
17+
if (x.isDigits()) {
18+
x.toInt()
19+
} else {
20+
registers.getValue(x)
21+
}
22+
23+
private fun emulate(a: Int = 0, b: Int = 0, c: Int = 0, d: Int = 0): Map<String, Int> {
24+
var pc = 0
25+
val registers = mutableMapOf("a" to a, "b" to b, "c" to c, "d" to d)
26+
27+
loop@ while (pc < instructions.size) {
28+
val (cmd, x, y) = instructions[pc]
29+
30+
when (cmd) {
31+
"cpy" -> registers[y] = getValue(registers, x)
32+
"inc" -> registers[x] = registers.getValue(x) + 1
33+
"dec" -> registers[x] = registers.getValue(x) - 1
34+
"jnz" -> if (getValue(registers, x) != 0) {
35+
pc += y.toInt()
36+
continue@loop
37+
}
38+
}
39+
40+
pc += 1
41+
}
42+
43+
return registers
44+
}
45+
}

src/main/resources/2016/12.txt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
cpy 1 a
2+
cpy 1 b
3+
cpy 26 d
4+
jnz c 2
5+
jnz 1 5
6+
cpy 7 c
7+
inc d
8+
dec c
9+
jnz c -2
10+
cpy a c
11+
inc a
12+
dec b
13+
jnz b -2
14+
cpy c b
15+
dec d
16+
jnz d -6
17+
cpy 17 c
18+
cpy 18 d
19+
inc a
20+
dec d
21+
jnz d -2
22+
dec c
23+
jnz c -5

src/test/kotlin/me/grison/aoc/y2016/AllDaysTest.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class AllDaysTest {
2222
// Answer({ Day09() }, 251, 898),
2323
// Answer({ Day10() }, 360154, 5103798),
2424
// Answer({ Day11() }, "vzbxxyzz", "vzcaabcc"),
25-
// Answer({ Day12() }, 119433, 68466),
25+
Answer({ Day12() }, 318117, 9227771),
2626
// Answer({ Day13() }, 664, 640),
2727
// Answer({ Day14() }, 2696, 1084),
2828
// Answer({ Day15() }, 222870, 117936),

0 commit comments

Comments
 (0)