Skip to content

Commit

Permalink
2024 - Day 18 - part 2 - added a sample using kotlin's binary search,…
Browse files Browse the repository at this point in the history
… but it's slower - possibly because I didn't bother to define the 0 case.
  • Loading branch information
fmmr committed Dec 18, 2024
1 parent 5e69cc6 commit c80ec75
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/main/kotlin/no/rodland/advent_2024/Day18.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,21 @@ class Day18(val input: List<String>, private val bytesToTake: Int, maxIndex: Int
}

override fun partTwo(): Pos {
// return binarySearchFromKotlin()
val findFirstPassingIndex: Int = binarySearch(bytesToTake, parsed.size - 1) { n: Int -> bfs(n).isEmpty() }
return parsed[findFirstPassingIndex - 1]
}

private fun binarySearchFromKotlin(): Pos {
// using kotlin's built in binary search
val hopp = (1..parsed.size)
.map { parsed.take(it) }
.binarySearch(bytesToTake) {
if (bfs(it.size, it.toSet()).isNotEmpty()) -1 else 1
}
return parsed[(hopp + 1) * -1]
}

private fun binarySearch(left: Int, right: Int, test: (index: Int) -> Boolean): Int {
if (left > right) return -1
val mid = left + (right - left) / 2
Expand Down

0 comments on commit c80ec75

Please sign in to comment.