Created
December 9, 2022 05:58
-
-
Save saidaspen/0467c374244fdba42473519d2da330aa to your computer and use it in GitHub Desktop.
AoC 2022 Day 09
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import se.saidaspen.aoc.util.* | |
import kotlin.math.absoluteValue | |
fun main() = Day09.run() | |
object Day09 : Day(2022, 9) { | |
override fun part1(): Any { | |
var h = P(0, 0) | |
var t = P(0, 0) | |
val visited = mutableSetOf<P<Int, Int>>() | |
visited.add(t) | |
for (l in input.lines()) { | |
repeat(ints(l)[0]) { | |
h = move(h, l[0]) | |
t = move(h, t) | |
visited.add(t) | |
} | |
} | |
return visited.size | |
} | |
override fun part2(): Any { | |
val snake = | |
mutableListOf(P(0, 0), P(0, 0), P(0, 0), P(0, 0), P(0, 0), P(0, 0), P(0, 0), P(0, 0), P(0, 0), P(0, 0)) | |
val visited = mutableSetOf<P<Int, Int>>() | |
for (l in input.lines()) { | |
repeat(ints(l)[0]) { | |
snake[0] = move(snake[0], l[0]) | |
for (i in 1 until snake.size) snake[i] = move(snake[i - 1], snake[i]) | |
visited.add(snake.last()) | |
} | |
} | |
return visited.size | |
} | |
private fun move(h: Pair<Int, Int>, dir: Char): Pair<Int, Int> { | |
return when (dir) { | |
'R' -> P(h.x + 1, h.y) | |
'L' -> P(h.x - 1, h.y) | |
'U' -> P(h.x, h.y - 1) | |
'D' -> P(h.x, h.y + 1) | |
else -> throw java.lang.RuntimeException("Unsupported move") | |
} | |
} | |
private fun move(h: Pair<Int, Int>, t: Pair<Int, Int>): Pair<Int, Int> { | |
var dx = h.x - t.x | |
var dy = h.y - t.y | |
var newT = t | |
if ((dx.absoluteValue == 1 && dy.absoluteValue == 1) || (dx.absoluteValue + dy.absoluteValue < 2)) { | |
return newT | |
} | |
dx = if (dx == 0) 0 else if (dx > 0) 1 else -1 | |
dy = if (dy == 0) 0 else if (dy > 0) 1 else -1 | |
if (dx == 0) { | |
newT = P(t.x, t.y + dy) | |
} else if (dy == 0) { | |
newT = P(t.x + dx, t.y) | |
} else { | |
newT = P(t.x + dx, t.y + dy) | |
} | |
return newT | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment