Skip to content

Commit 7d1d83e

Browse files
authored
Adds loop labeling for better visibility
Easier to understand which parts of the code is borrowed using TwoSum.
1 parent 5aa6e17 commit 7d1d83e

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,23 +36,23 @@ func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) ->
3636
let sorted = collection.sorted()
3737
var ret: [[T.Element]] = []
3838

39-
for l in sequence(first: sorted.startIndex, next: sorted.uniqueIndex(after:)) {
39+
ThreeSum: for l in sequence(first: sorted.startIndex, next: sorted.uniqueIndex(after:)) {
4040
var m = sorted.index(after: l)
4141
var r = sorted.index(before: sorted.endIndex)
4242

43-
while m < r {
43+
TwoSum: while m < r {
4444
let sum = sorted[l] + sorted[m] + sorted[r]
4545
switch target {
4646
case sum:
4747
ret.append([sorted[l], sorted[m], sorted[r]])
48-
guard let nextMid = sorted.uniqueIndex(after: m), let nextRight = sorted.uniqueIndex(before: r) else { break }
48+
guard let nextMid = sorted.uniqueIndex(after: m), let nextRight = sorted.uniqueIndex(before: r) else { break TwoSum }
4949
m = nextMid
5050
r = nextRight
5151
case ..<target:
52-
guard let nextMid = sorted.uniqueIndex(after: m) else { break }
52+
guard let nextMid = sorted.uniqueIndex(after: m) else { break TwoSum }
5353
m = nextMid
5454
case target...:
55-
guard let nextRight = sorted.uniqueIndex(before: r) else { break }
55+
guard let nextRight = sorted.uniqueIndex(before: r) else { break TwoSum }
5656
r = nextRight
5757
default: fatalError("Swift isn't smart enough to detect that this switch statement is exhausive")
5858
}

0 commit comments

Comments
 (0)