Advent of Code 2023 day 5
12/05/2025, 5:00 AMMichael de Kaste
12/05/2025, 5:14 AMDan Fingal-Surma
12/05/2025, 5:18 AMDan Fingal-Surma
12/05/2025, 5:31 AMDan Fingal-Surma
12/05/2025, 5:33 AMNeil Banman
12/05/2025, 5:33 AMbj0
12/05/2025, 5:33 AMvar list = fresh
var count = 0L
var end = 0L
while(list.isNotEmpty()) {
val first = list.first()
val start = max(first.first, end+1)
end = list.takeWhile { it.first <= first.last }.maxOf { it.last }
count += (end-start)+1
list = list.filter { it.last > end }
}
countNeil Banman
12/05/2025, 5:33 AMManel Martos
12/05/2025, 5:33 AMLongRange is missing a proper count method that returns a Long.bj0
12/05/2025, 5:34 AMDan Fingal-Surma
12/05/2025, 5:35 AMit != a check at firstbj0
12/05/2025, 5:53 AMtailrec a local functionJakub Gwóźdź
12/05/2025, 5:54 AMfun part2(data: String) = data.reader().readLines().takeWhile { it.isNotBlank() }
.map { it.split("-").let { (a, b) -> a.toLong()..b.toLong() } }
.sortedBy(LongRange::first)
.fold(0L to LongRange.EMPTY) { (count, range), next ->
when (next.first) {
in range if next.last in range -> count to range
in range -> count + (next.last - range.last) to range.first..next.last
else -> count + (next.last + 1 - next.first) to next
}
}.firstMarcin Wisniowski
12/05/2025, 5:58 AMMarcin Wisniowski
12/05/2025, 5:58 AMMarcin Wisniowski
12/05/2025, 5:59 AMJakub Gwóźdź
12/05/2025, 6:00 AMMarcin Wisniowski
12/05/2025, 6:02 AMMichael de Kaste
12/05/2025, 6:02 AMTreeMapLong, Boolean to track ranges.y9san9
12/05/2025, 6:05 AMNorbert Kiesel
12/05/2025, 6:06 AMLongRange.size as a standard property. But then I thought about e.g. 1..8 step 3 for which (1..8 step 3).count() correctly returns 3, but not sure what .size then should be.Dean Djermanović
12/05/2025, 6:08 AMTimmy
12/05/2025, 6:35 AMy9san9
12/05/2025, 7:09 AMAndriy
12/05/2025, 7:28 AMtailrec again 🤣
class Day05(input: String) {
val idRanges = input.substringBefore("\n\n").lines().map {
val range = it.trim().split("-")
range[0].toLong()..range[1].toLong()
}
val ids = input.substringAfter("\n\n").lines().map(String::toLong)
fun solvePart1(): Int {
return ids.count { id ->
idRanges.any { it.contains(id) }
}
}
fun solvePart2(): Long {
tailrec fun merge(ranges: List<LongRange>) : List<LongRange> {
var changed = false
val newRanges = ranges.fold(mutableListOf<LongRange>()) { acc, e ->
if (acc.isEmpty()) {
acc.add(e)
acc
} else {
val newAcc = mutableListOf<LongRange>()
var wasMerged = false
for (ae in acc) {
if (ae.last < e.first || e.last < ae.first) {
newAcc.add(ae)
continue
}
newAcc.add(minOf(ae.first, e.first)..maxOf(ae.last, e.last))
wasMerged = true
changed = true
}
if (!wasMerged) newAcc.add(e)
newAcc
}
}
return if (changed) merge(newRanges) else newRanges
}
return merge(idRanges)
.sumOf { it.last - it.first + 1 }
}
}phldavies
12/05/2025, 7:35 AMflatten().distinct().size while thinking "this is far too easy" before checking and realising the input ranges weren't small...
Sorting and tracking the last range end made it trivial though.
year 2025 day 5 part 1
Default took 376.05us 👑: 726
year 2025 day 5 part 2
Default took 138.067us 👑: 354226555270043Michael Böiers
12/05/2025, 9:05 AMimport kotlin.math.max
import kotlin.math.min
fun main() {
val (rangeData, ingredientsData) = generateSequence(::readLine).partition { "-" in it }
val ranges = rangeData.map { line -> line.split("-").map(String::toLong).let { it[0]..it[1] } }
ingredientsData.mapNotNull(String::toLongOrNull).count { i -> ranges.any { i in it } }
.also(::println)
fun LongRange.overlapsWith(other: LongRange) = this != other && (first in other || last in other)
fun LongRange.isIncludedIn(other: LongRange) = this != other && first in other && last in other
with(ranges.toMutableSet()) {
while (any { r -> none { r.overlapsWith(it) } }) {
filter { r -> any { r.isIncludedIn(it) } }.forEach(::remove)
val r = firstOrNull { r -> any { r.overlapsWith(it) } } ?: break
val r2 = first { r.overlapsWith(it) }
this += min(r.first, r2.first)..max(r.last, r2.last)
}
println(sumOf { it.last + 1 - it.first })
}
}demn
12/05/2025, 9:37 AMAnirudh
12/05/2025, 9:44 AMsortedFresh initially but I realise I don't need it.
• sorting first could reduce the number of recursive calls to make union-ranges but it works correctly even without it.Anirudh
12/05/2025, 9:46 AMif (newRange == normRange) {
return
}
vs
if (newRange == normRange) return
but many one-line-if's make it hard to read.
when would do but then I have a nested section which would look ugly anywayAnirudh
12/05/2025, 9:56 AMfun LongRange.hasOverlapWith(other: LongRange) = first <= other.last && last >= other.first
fun LongRange.getOverlapUnionWith(other: LongRange): LongRange =
listOf(first, other.first).min()..listOf(last, other.last).max()
private tailrec fun LongRange.addToNormalised(normalisedRanges: MutableList<LongRange>) {
for ((idx, normRange) in normalisedRanges.withIndex()) {
when {
!this.hasOverlapWith(normRange) -> continue
this == normRange -> return
}
val newRange = this.getOverlapUnionWith(normRange)
if (newRange == normRange) {
return
}
normalisedRanges.removeAt(idx)
return newRange.addToNormalised(normalisedRanges)
}
normalisedRanges.add(this)
}
fun partTwo(): Long {
val normalisedRanges: MutableList<LongRange> = mutableListOf()
freshRanges.forEach { freshRange ->
freshRange.addToNormalised(normalisedRanges)
}
return normalisedRanges.sumOf { it.last - it.first + 1 }
}Jaap Beetstra
12/05/2025, 10:03 AMprivate fun List<LongRange>.compact(): List<LongRange> =
this.sortedBy { it.first }.fold(emptyList()) { acc, current ->
when {
acc.isEmpty() -> acc + listOf(current)
acc.last().last < current.first -> acc + listOf(current)
current.last <= acc.last().last -> acc
else -> acc.dropLast(1) + listOf(acc.last().first..current.last())
}
}
Here I couldn’t use acc + current , because that would gave a List<Any> instead of the List<LongRange> I needed. The compiler picked the Collection<Any>.plus(Iterable<Any>) over Collection<LongRange>.plus(LongRange) . Interesting detail of the type resolver.ephemient
12/05/2025, 10:10 AMKarloti
12/05/2025, 10:20 AMAndriy
12/05/2025, 10:34 AMfun solvePart2(): Long {
fun ListLongRange.compact() = sequence {
if (isEmpty()) return@sequence
var optimized = first()
for (current in drop(1)) {
if (current.first <= optimized.last) {
optimized = optimized.first..maxOf(optimized.last, current.last)
} else {
yield(optimized)
optimized = current
}
}
yield(optimized)
}
fun LongRange.length(): Long = last - first + 1
return ranges.sortedBy { it.first }
.compact()
.sumOf { it.length() }
}Charles Flynn
12/05/2025, 11:36 AMAndriy
12/05/2025, 12:39 PMAndriy
12/05/2025, 1:53 PMfold usage, so optimized it a bit with mutable list:
private fun ListLongRange.compact(): ListLongRange =
sortedBy { it.first }.fold(mutableListOfLongRange()) { acc, current ->
when {
acc.isEmpty() -> acc.apply { add(current) }
acc.last().last < current.first -> acc.apply { add(current) }
current.last = acc.last().last - acc
else -> acc.apply {
val last = removeLast()
add(last.first..current.last)
}
}
}Michael de Kaste
12/05/2025, 1:55 PMfoldApply(function: (R, T) -> Unit)Max Thiele
12/05/2025, 4:07 PMTreeMap gives me binary search for free I guess:
private fun ListLongRange.merged(): TreeMapLong, Long {
val treeMap = TreeMapLong, Long()
val q = ArrayDeque(sortedBy { it.first })
while (q.isNotEmpty()) {
val elem = q.removeFirst()
var end = elem.last
while (q.isNotEmpty() && q.first().first <= end) {
end = max(end, q.removeFirst().last)
}
treeMap[elem.first] = end
}
return treeMap
}
Gets fairly fast:
Part 1 median: 63.032us
Part 2 median: 34.909uskingsley
12/05/2025, 4:38 PMkqr
12/05/2025, 5:13 PMoverride fun solvePart2(): Long {
val sortedByStart = freshIdRanges.sortedBy { it.first() }
val compactedRanges = mutableListOf<LongRange>()
var processedRange: LongRange = LongRange.EMPTY
sortedByStart.forEach { range ->
if (range.overlap(processedRange)) {
processedRange = processedRange.merge(range)
} else {
compactedRanges.add(processedRange)
processedRange = range
}
}
compactedRanges.add(processedRange)
return compactedRanges.sumOf { it.last - it.first + 1 }
}
fun LongRange.overlap(other: LongRange): Boolean {
return first <= other.last && last >= other.first
}
fun LongRange.merge(other: LongRange): LongRange {
return LongRange(min(first, other.first), max(last, other.last))
}Paul Woitaschek
12/05/2025, 9:11 PM