Advertisement
hrabrica

AoC | Day 5 | Part 2

Dec 5th, 2023
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. package year_2023.day_5
  2.  
  3. import kotlin.math.absoluteValue
  4.  
  5. fun partTwo() {
  6. println("[2023] Day five, part two...")
  7.  
  8. val inputData = input()
  9.  
  10. fun getMap(mapName: String): List<Pair<LongRange, LongRange>> {
  11. val map = inputData.split("\n\n")
  12. .single { it.contains(mapName) }
  13. .substringAfter("$mapName map:")
  14. .trim()
  15. .split("\n")
  16. .map { it.split(" ") }
  17. .map {
  18. val startSource = it[1].toLong()
  19. val startTarget = it[0].toLong()
  20. val range = it[2].toLong()
  21. (startSource until startSource + range) to (startTarget until startTarget + range)
  22. }
  23.  
  24. return map
  25. }
  26.  
  27. val seeds = inputData.split("\n\n")[0]
  28. .substringAfter(":")
  29. .trim()
  30. .split(" ")
  31. .map { it.toLong() }
  32. .windowed(2, 2)
  33. .map {
  34. it[0] until it[0] + it[1]
  35. }
  36.  
  37. val seedToSoilRanges = getMap("seed-to-soil")
  38. val soilToFertilizerRanges = getMap("soil-to-fertilizer")
  39. val fertilizerToWaterRanges = getMap("fertilizer-to-water")
  40. val waterToLightRanges = getMap("water-to-light")
  41. val lightToTemperatureRanges = getMap("light-to-temperature")
  42. val temperatureToHumidityRanges = getMap("temperature-to-humidity")
  43. val humidityToLocationRanges = getMap("humidity-to-location")
  44.  
  45. fun getPrevious(map: List<Pair<LongRange, LongRange>>, source: Long): Long {
  46. val ranges = map.firstOrNull { it.second.contains(source) }
  47. ?: return source
  48.  
  49. return ranges.first.first + (source - ranges.second.first).absoluteValue
  50. }
  51.  
  52. var minValue = Long.MAX_VALUE
  53.  
  54. for (location in 1 until 100_000_000L) {
  55. val humidity = getPrevious(humidityToLocationRanges, location)
  56. val temperature = getPrevious(temperatureToHumidityRanges, humidity)
  57. val light = getPrevious(lightToTemperatureRanges, temperature)
  58. val water = getPrevious(waterToLightRanges, light)
  59. val fertilizer = getPrevious(fertilizerToWaterRanges, water)
  60. val soil = getPrevious(soilToFertilizerRanges, fertilizer)
  61. val seed = getPrevious(seedToSoilRanges, soil)
  62.  
  63. if (seeds.any { it.contains(seed) }) {
  64. minValue = location
  65. break
  66. }
  67. }
  68.  
  69. println(minValue)
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement