<Advent of Code 2025 day 5> (spoilers) :thread:
# advent-of-code
a
m
feels a bit like cheating for me today since I've worked on custom range implementation 🫥 I'll have to rewrite without it now 😛
d
Outer while-loop runs 4 times
ranges has to be snapshot to prevent concurrent modification during iteration
n
Untitled
b
i tried a tailrec but was getting stack overflows (??), so i just did a quick and dirty mutable loop
Copy code
var 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 }
}
count
👍 1
n
Started late due to daughter having the temerity to ask for iPad time right at 9:00pm. But a very easy one. I would have thought part 2 would take more time because I have a very clumsy "merge and delete elements from a list until done" algorithm. But it's 3ms, which is a rounding error for cold Kotlin runtimes. So probably not worth refining. One of those problems where I was so confident of no mistakes that I didn't bother running the examples. Not to squeeze out a faster time, just lazy and confident.
m
Yeah! But I feel that
LongRange
is missing a proper
count
method that returns a
Long
.
➕ 4
👍 1
b
it was easy but i kept making simple errors on the second one, perhaps because it was too easy
d
I missed that
it != a
check at first
b
oh, apparently it didn't want to
tailrec
a local function
j
part 2 today cheated a bit because I sorted the ranges to make "when" part more maintainable:
Copy code
fun 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
        }
    }.first
m
Part 1
Part 2
Could be shorter... but that's what I came up with.
j
yeah without sort you need to keep track of all ranges so far. after all, I think I prefer mine 🙂
m
Sorting is a good idea, I wish my 5AM brain thought of it. 😄
m
a rough distilled version of what I had. Uses a
TreeMapLong, Boolean
to track ranges.
y
Binary search thing today
n
Yeah, also thought I would like to see
LongRange.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.
d
also used sorting and merged overlapping intervals for part 2
t
The amount of time I spent on trying to merge the ranges into one list of non-overlapping ranges is brutal, considering how simple part 2 becomes with sorting + index pointer 🙈
y
a
No chance not to use
tailrec
again 🤣
Copy code
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 }
    }
}
p
🙋 who else tried brute forcing part2 with
flatten().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.
Copy code
year 2025 day 5 part 1
	 Default took 376.05us 👑: 726
year 2025 day 5 part 2
	 Default took 138.067us 👑: 354226555270043
🙋 5
m
Short and sweet, it's all ranges and streaming 🙂
Copy code
import 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 })
    }
}
d
solved pt.1 by usual bruteforce and pt.2 by merging ranges just like from typical leetcode task
a
ashamed to say I took so long to do this one that I could've finished it faster in Excel/spreadsheets. • got hung up on trying to 'split' overlapping ranges before I realised I should just remove the original and add the union of them. • I had kept a
sortedFresh
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.
and spent a good 10 mins trying to decide which of these I like more:
Copy code
if (newRange == normRange) {
    return
}
vs
Copy code
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 anyway
here's mine, a bit too imperative imho:
Copy code
fun 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 }
}
j
Not too difficult. One interesting ‘feature’ I encountered was how the compiler did not resolve the correct operator overload. I use a compact step to combine the ranges, with a fold on the list:
Copy code
private 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.
e
binarySearch ❤️
k
I solved the problem using an O(N log N) sort-and-merge approach paired with binary search, which handled the one-million-record worst-case input in just 180 milliseconds. https://github.com/karloti/aoc-2025-in-kotlin/blob/main/src/Day05.kt
a
Ahh... 😵‍💫 during swimming in the pool 🏊 I've realized that my prev. logic might be significant improved with preliminary range sorting:
Copy code
fun 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() }
    }
c
That felt quite simple. Was this intended as the yearly "this isn't going to work if you just put all the numbers in a set - it'll all blow up" puzzle?
a
@Karloti binary search for the part 1 looks a bit over engineered IMHO 🫣
@Jaap Beetstra like your
fold
usage, so optimized it a bit with mutable list:
Copy code
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)
            }
        }
    }
🙌 1
m
above example shows perfectly why I feel like, even though mutability is not a functional aspect, we really do need a apply version of our aggregates
Copy code
foldApply(function: (R, T) -> Unit)
K 1
m
I simply put my merged ranges into a
TreeMap
gives me binary search for free I guess:
Copy code
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:
Copy code
Part 1 median:        63.032us
Part 2 median:        34.909us
k
k
late to the party
Copy code
override 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))
}
p