Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package year_2023.day_5
- import kotlin.math.absoluteValue
- fun partTwo() {
- println("[2023] Day five, part two...")
- val inputData = input()
- fun getMap(mapName: String): List<Pair<LongRange, LongRange>> {
- val map = inputData.split("\n\n")
- .single { it.contains(mapName) }
- .substringAfter("$mapName map:")
- .trim()
- .split("\n")
- .map { it.split(" ") }
- .map {
- val startSource = it[1].toLong()
- val startTarget = it[0].toLong()
- val range = it[2].toLong()
- (startSource until startSource + range) to (startTarget until startTarget + range)
- }
- return map
- }
- val seeds = inputData.split("\n\n")[0]
- .substringAfter(":")
- .trim()
- .split(" ")
- .map { it.toLong() }
- .windowed(2, 2)
- .map {
- it[0] until it[0] + it[1]
- }
- val seedToSoilRanges = getMap("seed-to-soil")
- val soilToFertilizerRanges = getMap("soil-to-fertilizer")
- val fertilizerToWaterRanges = getMap("fertilizer-to-water")
- val waterToLightRanges = getMap("water-to-light")
- val lightToTemperatureRanges = getMap("light-to-temperature")
- val temperatureToHumidityRanges = getMap("temperature-to-humidity")
- val humidityToLocationRanges = getMap("humidity-to-location")
- fun getPrevious(map: List<Pair<LongRange, LongRange>>, source: Long): Long {
- val ranges = map.firstOrNull { it.second.contains(source) }
- ?: return source
- return ranges.first.first + (source - ranges.second.first).absoluteValue
- }
- var minValue = Long.MAX_VALUE
- for (location in 1 until 100_000_000L) {
- val humidity = getPrevious(humidityToLocationRanges, location)
- val temperature = getPrevious(temperatureToHumidityRanges, humidity)
- val light = getPrevious(lightToTemperatureRanges, temperature)
- val water = getPrevious(waterToLightRanges, light)
- val fertilizer = getPrevious(fertilizerToWaterRanges, water)
- val soil = getPrevious(soilToFertilizerRanges, fertilizer)
- val seed = getPrevious(seedToSoilRanges, soil)
- if (seeds.any { it.contains(seed) }) {
- minValue = location
- break
- }
- }
- println(minValue)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement