Advertisement
hrabrica

AoC | Day 5 | Part 1

Dec 5th, 2023
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. package year_2023.day_5
  2.  
  3. import kotlin.math.absoluteValue
  4.  
  5. fun partOne() {
  6. println("[2023] Day five, part one...")
  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.  
  33.  
  34. val seedToSoilRanges = getMap("seed-to-soil")
  35. val soilToFertilizerRanges = getMap("soil-to-fertilizer")
  36. val fertilizerToWaterRanges = getMap("fertilizer-to-water")
  37. val waterToLightRanges = getMap("water-to-light")
  38. val lightToTemperatureRanges = getMap("light-to-temperature")
  39. val temperatureToHumidityRanges = getMap("temperature-to-humidity")
  40. val humidityToLocationRanges = getMap("humidity-to-location")
  41.  
  42. val seedToLocationMap = mutableMapOf<Long, Long>()
  43.  
  44. fun getNext(map: List<Pair<LongRange, LongRange>>, source: Long): Long {
  45. val ranges = map.firstOrNull { it.first.contains(source) }
  46. ?: return source
  47.  
  48. return ranges.second.first + (source - ranges.first.first).absoluteValue
  49. }
  50.  
  51. seeds.forEach { seed ->
  52. val soil = getNext(seedToSoilRanges, seed)
  53. val fertilizer = getNext(soilToFertilizerRanges, soil)
  54. val water = getNext(fertilizerToWaterRanges, fertilizer)
  55. val light = getNext(waterToLightRanges, water)
  56. val temperature = getNext(lightToTemperatureRanges, light)
  57. val humidity = getNext(temperatureToHumidityRanges, temperature)
  58. val location = getNext(humidityToLocationRanges, humidity)
  59.  
  60. seedToLocationMap[seed] = location
  61. }
  62.  
  63. println(seedToLocationMap.minBy { it.value }.value)
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement