Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Test
- fun part1() {
- println("Part 1: ${calculateRisk(data)}")
- }
- @Test
- fun part2() {
- val basins = lowestPoints(data).map { findBasin(data, it).size }.sorted().reversed()
- println("Part 2 ${basins[0] * basins[1] * basins[2]}")
- }
- private fun calculateRisk(cave: List<List<Int>>) =
- lowestPoints(cave).sumBy { cave.heightAt(it) + 1 }
- private fun lowestPoints(cave: List<List<Int>>): List<Int> {
- return (0 until cave.allPoints).filter { position ->
- val pointHeight = cave.heightAt(position)
- pointHeight < cave.heightLeftOf(position) &&
- pointHeight < cave.heightRighttOf(position) &&
- pointHeight < cave.heightAbove(position) &&
- pointHeight < cave.heightBelow(position)
- }
- }
- private fun findBasin(cave: List<List<Int>>, position: Int, basin: Set<Int> = emptySet()): Set<Int> {
- if (basin.contains(position) || cave.heightAt(position) == 9) return basin
- var basinResult = basin + position
- if (position % cave.width > 0) basinResult = findBasin(cave, position - 1, basinResult)
- if (position % cave.width < cave.width - 1) basinResult = findBasin(cave, position + 1, basinResult)
- if (position / cave.width > 0) basinResult = findBasin(cave, position - cave.width, basinResult)
- if (position / cave.width < cave.size - 1) basinResult = findBasin(cave, position + cave.width, basinResult)
- return basinResult
- }
- private val List<List<Int>>.width get() = this[0].size
- private val List<List<Int>>.allPoints get() = width * size
- private fun List<List<Int>>.heightAt(position: Int) = this[position / width][position % width] - 48
- private fun List<List<Int>>.heightLeftOf(position: Int) = if (position % width == 0) 9 else heightAt(position - 1)
- private fun List<List<Int>>.heightRighttOf(position: Int) = if (position % width == width - 1) 9 else heightAt(position + 1)
- private fun List<List<Int>>.heightAbove(position: Int) = if (position / width == 0) 9 else heightAt(position - width)
- 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