Stopping a Search Across Nested Loops
Stopping at the first matching pair requires leaving both loops or expressing the search as an operation with a result.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Find the nearest break
Search rows in order for the first occupied seat. A break in the inner loop ends that row's scan and then the outer loop moves to another row. Break behavior explains why a later row can overwrite the earlier match.
Return a complete witness
A helper can return the row and column at the match and return an explicit missing result after both loops finish. Test rows with matches at distinct positions and a case with none. First-match scans define why the visitation order is part of the helper's contract.[1]
Predict exactly how many candidates are checked
Consider a row-by-row search of [[4, 9], [], [9, 2]] for nine. The first hit is row zero, column one after two comparisons. In Python a break in the inner loop exits that loop alone. If the outer loop continues and overwrites the result, it can report the nine in row two. Returning the coordinates from a small search function ends both loops and gives callers a simple contract. Test an empty table and a hit in the last column of the last row to confirm that the search continues when it should. See exiting a loop for the scope of break.
Clarify whether iteration order is a public promise
A caller asking for any matching entry permits a different search order. A caller that expects the first match in row-major order may use that position to report a deterministic diagnostic. Replacing the row container with a hash-based collection or splitting the search among workers can change the first reported result. A sentinel such as None is useful when a valid position can include zero, since a falsey coordinate component still represents a hit. If matches are rare, most executions still inspect nearly the entire table. The nested loops define that worst-case cost.