vbe_elvis

2021 Day 8

Dec 9th, 2021 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.22 KB | None | 0 0
  1.    @Test
  2.     fun part1() {
  3.         println("Part 1: ${calculateRisk(data)}")
  4.     }
  5.  
  6.     @Test
  7.     fun part2() {
  8.         val basins = lowestPoints(data).map { findBasin(data, it).size }.sorted().reversed()
  9.         println("Part 2 ${basins[0] * basins[1] * basins[2]}")
  10.     }
  11.  
  12.     private fun calculateRisk(cave: List<List<Int>>) =
  13.         lowestPoints(cave).sumBy { cave.heightAt(it) + 1 }
  14.  
  15.     private fun lowestPoints(cave: List<List<Int>>): List<Int> {
  16.         return (0 until cave.allPoints).filter { position ->
  17.             val pointHeight = cave.heightAt(position)
  18.             pointHeight < cave.heightLeftOf(position) &&
  19.             pointHeight < cave.heightRighttOf(position) &&
  20.             pointHeight < cave.heightAbove(position) &&
  21.             pointHeight < cave.heightBelow(position)
  22.         }
  23.     }
  24.  
  25.     private fun findBasin(cave: List<List<Int>>, position: Int, basin: Set<Int> = emptySet()): Set<Int> {
  26.         if (basin.contains(position) || cave.heightAt(position) == 9)  return basin
  27.         var basinResult = basin + position
  28.         if (position % cave.width > 0) basinResult = findBasin(cave, position - 1, basinResult)
  29.         if (position % cave.width < cave.width - 1) basinResult = findBasin(cave, position + 1, basinResult)
  30.         if (position / cave.width > 0) basinResult = findBasin(cave, position - cave.width, basinResult)
  31.         if (position / cave.width < cave.size - 1) basinResult = findBasin(cave, position + cave.width, basinResult)
  32.         return basinResult
  33.     }
  34.  
  35.     private val List<List<Int>>.width get() = this[0].size
  36.     private val List<List<Int>>.allPoints get() = width * size
  37.     private fun List<List<Int>>.heightAt(position: Int) = this[position / width][position % width] - 48
  38.     private fun List<List<Int>>.heightLeftOf(position: Int) = if (position % width == 0) 9 else heightAt(position - 1)
  39.     private fun List<List<Int>>.heightRighttOf(position: Int) = if (position % width == width - 1) 9 else heightAt(position + 1)
  40.     private fun List<List<Int>>.heightAbove(position: Int) = if (position / width == 0) 9 else heightAt(position - width)
  41.     private fun List<List<Int>>.heightBelow(position: Int) = if (position / width == size - 1) 9 else heightAt(position + width)
Add Comment
Please, Sign In to add comment