Skip to content

Instantly share code, notes, and snippets.

@bsautner
Last active December 9, 2022 18:53
Show Gist options
  • Save bsautner/5c25888924acc7a7cab3ef35f12459fc to your computer and use it in GitHub Desktop.
Save bsautner/5c25888924acc7a7cab3ef35f12459fc to your computer and use it in GitHub Desktop.
import java.io.File
import kotlin.math.abs
class AOC9 {
fun process() {
val input = File("/home/ben/aoc/input-9.txt")
val sample = input.useLines { it.toList() }
val p1 = mutableListOf<Pair<Int, Int>>()
repeat((0..1).count()) { p1.add(Pair(0, 0)) }
val p2 = mutableListOf<Pair<Int, Int>>()
repeat((0..9).count()) { p2.add(Pair(0, 0)) }
println("Part1: ${scan(p1, sample)}")
println("Part2: ${scan(p2, sample)}")
}
private fun scan(r: MutableList<Pair<Int, Int>>, input: List<String>): Int {
val pos = mutableSetOf<Pair<Int, Int>>()
pos.add(r.last())
input.forEach {
val cmd = it.split(" ")
(1..cmd[1].toInt()).forEach { _ ->
r[0] = processStep(cmd[0], r[0])
(0 until r.size - 1).forEachIndexed { index, _ ->
val newPositions =
tail(r[index], r[index + 1])
r[index + 1] = newPositions
}
pos.add(r.last())
}
}
return pos.size
}
private fun tail(
head: Pair<Int, Int>,
tail: Pair<Int, Int>
): Pair<Int, Int> {
return when {
abs((head.first - tail.first)) > 1 || abs((head.second - tail.second)) > 1 -> {
when {
head.first == tail.first -> {
Pair(
tail.first,
if (head.second > tail.second) tail.second + 1 else tail.second - 1
)
}
head.second == tail.second -> {
Pair(
if (head.first > tail.first) tail.first + 1 else tail.first - 1,
tail.second
)
}
else -> {
val xDiff = (head.first - tail.first)
val yDiff = (head.second - tail.second)
val changeX = abs(xDiff) > 1 || (abs(xDiff) > 0 && abs(yDiff) > 1)
val changeY = abs(yDiff) > 1 || (abs(yDiff) > 0 && abs(xDiff) > 1)
Pair(
if (changeX) tail.first + (if (xDiff < 0) -1 else 1) else tail.first,
if (changeY) tail.second + (if (yDiff < 0) -1 else 1) else tail.second,
)
}
}
}
else -> tail
}
}
private fun processStep(step: String, pos: Pair<Int, Int>): Pair<Int, Int> {
val (x, y) = pos
return when (step) {
"U" -> pos.copy(second = y - 1)
"D" -> pos.copy(second = y + 1)
"L" -> pos.copy(first = x - 1)
"R" -> pos.copy(first = x + 1)
else -> { throw IllegalStateException() }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment