Skip to content

Commit 8c10fbd

Browse files
authored
Repositions index traversal of l
Seems like a good use case for `defer`... giving the index traversal more visibility by putting it next to the `while` loop. Reads a bit more like for loops now, where exit condition and traversal procedure can be understood in 1 line.
1 parent 1c4ce41 commit 8c10fbd

File tree

1 file changed

+2
-3
lines changed

1 file changed

+2
-3
lines changed

3Sum and 4Sum/3Sum.playground/Contents.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,11 @@ func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) ->
3232
var ret: [[T.Element]] = []
3333
var l = sorted.startIndex
3434

35-
while l < sorted.endIndex {
35+
while l < sorted.endIndex { defer { sorted.formUniqueIndex(after: &l) }
3636
var m = sorted.index(after: l)
3737
var r = sorted.index(before: sorted.endIndex)
3838

39-
while m < r && r < sorted.endIndex {
39+
while m < r && r < sorted.endIndex {
4040
let sum = sorted[l] + sorted[m] + sorted[r]
4141
switch target {
4242
case sum:
@@ -50,7 +50,6 @@ func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) ->
5050
default: fatalError("Swift isn't smart enough to detect that this switch statement is exhausive")
5151
}
5252
}
53-
sorted.formUniqueIndex(after: &l)
5453
}
5554

5655
return ret

0 commit comments

Comments
 (0)