Skip to content

Commit a1d0e3f

Browse files
committed
edit Selection Sampling for clarity as described in kodecocodes#475
1 parent 5dc06ac commit a1d0e3f

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

Selection Sampling/SelectionSampling.playground/Contents.swift

+4-4
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,19 @@ func select<T>(from a: [T], count requested: Int) -> [T] {
3232
var b = [T]()
3333

3434
while selected < requested {
35-
examined += 1
36-
3735
// Calculate random variable 0.0 <= r < 1.0 (exclusive!).
3836
let r = Double(arc4random()) / 0x100000000
3937

40-
let leftToExamine = a.count - examined + 1
38+
let leftToExamine = a.count - examined
4139
let leftToAdd = requested - selected
4240

4341
// Decide whether to use the next record from the input.
4442
if Double(leftToExamine) * r < Double(leftToAdd) {
4543
selected += 1
46-
b.append(a[examined - 1])
44+
b.append(a[examined])
4745
}
46+
47+
examined += 1
4848
}
4949
return b
5050
}

Selection Sampling/SelectionSampling.swift

+4-4
Original file line numberDiff line numberDiff line change
@@ -61,19 +61,19 @@ func select<T>(from a: [T], count requested: Int) -> [T] {
6161
var b = [T]()
6262

6363
while selected < requested {
64-
examined += 1
65-
6664
// Calculate random variable 0.0 <= r < 1.0 (exclusive!).
6765
let r = Double(arc4random()) / 0x100000000
6866

69-
let leftToExamine = a.count - examined + 1
67+
let leftToExamine = a.count - examined
7068
let leftToAdd = requested - selected
7169

7270
// Decide whether to use the next record from the input.
7371
if Double(leftToExamine) * r < Double(leftToAdd) {
7472
selected += 1
75-
b.append(a[examined - 1])
73+
b.append(a[examined])
7674
}
75+
76+
examined += 1
7777
}
7878
return b
7979
}

0 commit comments

Comments
 (0)