Advertisement
Guest User

AOC - 2024 day 18

a guest
Dec 18th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.24 KB | Software | 0 0
  1. package Y2024.D18
  2.  
  3. class RamFall(lines: List<String>, val width: Int, val height: Int) {
  4.     val bytes = lines.map { it.split(",").map(String::toInt) }.map { it[1] to it[0] }
  5.  
  6.     fun runElvesRun(): Int? {
  7.         return walkTheRam(bytes.take(1024))
  8.     }
  9.  
  10.     fun whenAreWeBlocked(): String {
  11.         var upperBound = bytes.size
  12.         var lowerBound = 0
  13.         while (lowerBound != upperBound) {
  14.             val numberOfBytes = (lowerBound + upperBound) / 2
  15.             if (walkTheRam(bytes.take(numberOfBytes)) == null) upperBound = numberOfBytes - 1
  16.             else lowerBound = numberOfBytes
  17.         }
  18.         return "" + bytes[lowerBound].second + "," + bytes[lowerBound].first
  19.     }
  20.  
  21.     private fun walkTheRam(fallenBytes: List<Pair<Int, Int>>): Int? {
  22.         val nextPositions = mutableListOf(0 to 0)
  23.         val visited = mutableMapOf((0 to 0) to 0)
  24.  
  25.         while (nextPositions.isNotEmpty()) {
  26.             val pos = nextPositions.removeAt(0)
  27.             val step = visited[pos]!!
  28.             pos.findNeighbours()
  29.                 .filter { !fallenBytes.contains(it) }
  30.                 .filter { (visited[it] ?: Int.MAX_VALUE) > step + 1 }
  31.                 .forEach {
  32.                     visited[it] = step + 1
  33.                     nextPositions.add(it)
  34.                 }
  35.         }
  36.         return visited[height to width]
  37.     }
  38.  
  39.     private fun Pair<Int, Int>.findNeighbours(): List<Pair<Int, Int>> {
  40.         return listOf(
  41.             this + (-1 to 0),
  42.             this + (1 to 0),
  43.             this + (0 to -1),
  44.             this + (0 to 1)
  45.         )
  46.             .filter { it.first in 0..height && it.second in 0..width }
  47.     }
  48.  
  49.     private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
  50.         return first + other.first to second + other.second
  51.     }
  52.  
  53.     private fun printRam(fallenBytes: List<Pair<Int, Int>>, visited: MutableMap<Pair<Int, Int>, Int>) {
  54.         println("Number of bytes: " + fallenBytes.size)
  55.         repeat(height+1) {y ->
  56.             repeat(width+1) { x ->
  57.                 if (fallenBytes.contains(y to x)) print("|")
  58.                 else if (visited.keys.contains(y to x)) print("O")
  59.                 else print(".")
  60.             }
  61.             println()
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement