Skip to content

Commit 62aab8a

Browse files
committed
Add 2023 Day 05 Part 2 solution
1 parent 78c86a7 commit 62aab8a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

adventofcode2023/Day05.kt

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,70 @@ object Day05 {
2222
number
2323
})
2424
}
25+
26+
fun part2(inputs: List<String>) {
27+
fun getRangesMaps(): Array<MutableList<LongArray>> {
28+
val rangesMaps = Array<MutableList<LongArray>>(7) { mutableListOf() }
29+
var mapIndex = 0
30+
31+
for (i in inputs.indices.drop(2)) {
32+
if (inputs[i] == "")
33+
mapIndex++
34+
else if (inputs[i].split(" ").size == 3)
35+
rangesMaps[mapIndex].add(inputs[i].split(" ").map { it.toLong() }.toLongArray())
36+
}
37+
38+
return rangesMaps
39+
}
40+
41+
fun getSeedRanges(): List<Pair<Long, Long>> {
42+
val rangesLine = inputs[0].split(" ").drop(1)
43+
val ranges: MutableList<Pair<Long, Long>> = mutableListOf()
44+
45+
for (i in rangesLine.indices) {
46+
if (i % 2 == 0) ranges.add(
47+
Pair(
48+
rangesLine[i].toLong(),
49+
rangesLine[i].toLong() + rangesLine[i + 1].toLong()
50+
)
51+
)
52+
}
53+
54+
return ranges
55+
}
56+
57+
val rangesMaps = getRangesMaps()
58+
val seedRanges = getSeedRanges()
59+
60+
fun getSeedFromLocation(location: Long): Long {
61+
var number = location
62+
var mapIndex = rangesMaps.size - 1
63+
64+
while (mapIndex >= 0) {
65+
for (line in rangesMaps[mapIndex]) {
66+
if (line[0] <= number && line[0] + line[2] > number) {
67+
number = line[1] + number - line[0]
68+
break
69+
}
70+
}
71+
mapIndex--
72+
}
73+
74+
return number
75+
}
76+
77+
for (location in 0L..Long.MAX_VALUE) {
78+
val number = getSeedFromLocation(location)
79+
if (seedRanges.any { number >= it.first && number < it.second }) {
80+
println(location)
81+
break
82+
}
83+
}
84+
}
2585
}
2686

2787
fun main() {
2888
val inputs = File("resources/adventofcode2023/Day05.txt").readLines()
2989
Day05.part1(inputs)
90+
Day05.part2(inputs)
3091
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy