Skip to content

Commit

Permalink
day 10
Browse files Browse the repository at this point in the history
  • Loading branch information
kgeri committed Dec 10, 2022
1 parent e5d0761 commit c3acfa4
Show file tree
Hide file tree
Showing 2 changed files with 199 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/main/kotlin/me/gergo/Aoc10.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package me.gergo

import java.io.File

fun main() {
val instructions = File("src/main/resources/input10.txt").readLines()
.map(::parseInstr)

// Part One
val result = listOf(20, 60, 100, 140, 180, 220).map {
val cpu = CPU(instructions)
for (c in 1 until it) cpu.step()
it * cpu.x
}.sum()
println(result)

// Part Two
val cpu = CPU(instructions)
CRT(40, 6, cpu).draw()
}

sealed class Instr(val duration: Int)
object Noop : Instr(1)
data class Addx(val value: Int) : Instr(2)

private class CPU(private val instructions: List<Instr>) {
private var instructionPointer = 0
private var remainingDuration = instructions[instructionPointer].duration
var x = 1

fun step() {
remainingDuration--
if (remainingDuration > 0) {
return
}

when (val instr = instructions[instructionPointer]) {
is Noop -> {}
is Addx -> x += instr.value
}
if (instructionPointer >= instructions.size - 1) return
instructionPointer++
remainingDuration = instructions[instructionPointer].duration
}
}

private class CRT(private val width: Int, private val height: Int, private val cpu: CPU) {
fun draw() {
for (y in 1..6) {
for (x in 0..39) {
print(if (cpu.x - 1 <= x && x <= cpu.x + 1) '#' else '.')
cpu.step()
}
println()
}
}
}

fun parseInstr(line: String): Instr {
val tokens = line.split(" ")
return if (tokens[0] == "noop") Noop
else Addx(tokens[1].toInt())
}
136 changes: 136 additions & 0 deletions src/main/resources/input10.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
noop
noop
addx 5
addx 3
noop
addx 14
addx -12
noop
addx 5
addx 1
noop
addx 19
addx -15
noop
noop
noop
addx 7
addx -1
addx 4
noop
noop
addx 5
addx 1
addx -38
noop
addx 21
addx -18
addx 2
addx 2
noop
addx 3
addx 5
addx -6
addx 11
noop
addx 2
addx 19
addx -18
noop
addx 8
addx -3
addx 2
addx 5
addx 2
addx 3
addx -2
addx -38
noop
addx 3
addx 4
addx 5
noop
addx -2
addx 5
addx -8
addx 12
addx 3
addx -2
addx 5
addx 11
addx -31
addx 23
addx 4
noop
noop
addx 5
addx 3
addx -2
addx -37
addx 1
addx 5
addx 2
addx 12
addx -10
addx 3
addx 4
addx -2
noop
addx 6
addx 1
noop
noop
noop
addx -2
addx 7
addx 2
noop
addx 3
addx 3
addx 1
noop
addx -37
addx 2
addx 5
addx 2
addx 32
addx -31
addx 5
addx 2
addx 9
addx 9
addx -15
noop
addx 3
addx 2
addx 5
addx 2
addx 3
addx -2
addx 2
addx 2
addx -37
addx 5
addx -2
addx 2
addx 5
addx 2
addx 16
addx -15
addx 4
noop
addx 1
addx 2
noop
addx 3
addx 5
addx -1
addx 5
noop
noop
noop
noop
addx 3
addx 5
addx -16
noop

0 comments on commit c3acfa4

Please sign in to comment.