Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Y2024.D18
- class RamFall(lines: List<String>, val width: Int, val height: Int) {
- val bytes = lines.map { it.split(",").map(String::toInt) }.map { it[1] to it[0] }
- fun runElvesRun(): Int? {
- return walkTheRam(bytes.take(1024))
- }
- fun whenAreWeBlocked(): String {
- var upperBound = bytes.size
- var lowerBound = 0
- while (lowerBound != upperBound) {
- val numberOfBytes = (lowerBound + upperBound) / 2
- if (walkTheRam(bytes.take(numberOfBytes)) == null) upperBound = numberOfBytes - 1
- else lowerBound = numberOfBytes
- }
- return "" + bytes[lowerBound].second + "," + bytes[lowerBound].first
- }
- private fun walkTheRam(fallenBytes: List<Pair<Int, Int>>): Int? {
- val nextPositions = mutableListOf(0 to 0)
- val visited = mutableMapOf((0 to 0) to 0)
- while (nextPositions.isNotEmpty()) {
- val pos = nextPositions.removeAt(0)
- val step = visited[pos]!!
- pos.findNeighbours()
- .filter { !fallenBytes.contains(it) }
- .filter { (visited[it] ?: Int.MAX_VALUE) > step + 1 }
- .forEach {
- visited[it] = step + 1
- nextPositions.add(it)
- }
- }
- return visited[height to width]
- }
- private fun Pair<Int, Int>.findNeighbours(): List<Pair<Int, Int>> {
- return listOf(
- this + (-1 to 0),
- this + (1 to 0),
- this + (0 to -1),
- this + (0 to 1)
- )
- .filter { it.first in 0..height && it.second in 0..width }
- }
- private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
- return first + other.first to second + other.second
- }
- private fun printRam(fallenBytes: List<Pair<Int, Int>>, visited: MutableMap<Pair<Int, Int>, Int>) {
- println("Number of bytes: " + fallenBytes.size)
- repeat(height+1) {y ->
- repeat(width+1) { x ->
- if (fallenBytes.contains(y to x)) print("|")
- else if (visited.keys.contains(y to x)) print("O")
- else print(".")
- }
- println()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement