Skip to content

Commit

Permalink
2024 - Day 18 - part 2 - rewrote to binary search for the index - 3.8…
Browse files Browse the repository at this point in the history
…ms instead of 1500ms.
  • Loading branch information
fmmr committed Dec 18, 2024
1 parent 4d03fb7 commit 5e69cc6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
17 changes: 14 additions & 3 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 {
val idx = (bytesToTake..parsed.size).first { n ->
bfs(n).isEmpty()
val findFirstPassingIndex: Int = binarySearch(bytesToTake, parsed.size - 1) { n: Int -> bfs(n).isEmpty() }
return parsed[findFirstPassingIndex - 1]
}

private fun binarySearch(left: Int, right: Int, test: (index: Int) -> Boolean): Int {
if (left > right) return -1
val mid = left + (right - left) / 2
return if (test(mid)) {
// Check if this is the first passing index or search the left half
val earlierIndex = binarySearch(left, mid - 1, test)
if (earlierIndex != -1) earlierIndex else mid
} else {
// Search the right half
binarySearch(mid + 1, right, test)
}
return parsed[idx - 1]
}

private fun bfs(n: Int, set: Set<Pos> = parsed.take(n).toSet()) = bfs(start, end, { p ->
Expand Down
3 changes: 1 addition & 2 deletions src/test/kotlin/no/rodland/advent_2024/Day18Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ internal class Day18Test {
{ Day18(data18, 1024, 70) },
{ Day18(test18, 12, 6) },
numTestPart1 = 20,
numTestPart2 = 1
numTestPart2 = 20
)

@Nested
Expand Down Expand Up @@ -77,7 +77,6 @@ internal class Day18Test {
}

@Test
@Slow(1500)
fun `18,2,live,1`() {
report(test.livePart2)
}
Expand Down

0 comments on commit 5e69cc6

Please sign in to comment.