Skip to content

Commit f75ebbd

Browse files
authored
Merge pull request kodecocodes#631 from mnespor/selection-sampling-475
edit Selection Sampling for clarity as described in kodecocodes#475
2 parents cc32ec5 + bed042c commit f75ebbd

File tree

3 files changed

+12
-12
lines changed

3 files changed

+12
-12
lines changed

Selection Sampling/README.markdown

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,17 +89,17 @@ func select<T>(from a: [T], count requested: Int) -> [T] {
8989
var b = [T]()
9090

9191
while selected < requested { // 1
92-
examined += 1
93-
9492
let r = Double(arc4random()) / 0x100000000 // 2
9593

96-
let leftToExamine = a.count - examined + 1 // 3
94+
let leftToExamine = a.count - examined // 3
9795
let leftToAdd = requested - selected
9896

9997
if Double(leftToExamine) * r < Double(leftToAdd) { // 4
10098
selected += 1
101-
b.append(a[examined - 1])
99+
b.append(a[examined])
102100
}
101+
102+
examined += 1
103103
}
104104
return b
105105
}

Selection Sampling/SelectionSampling.playground/Contents.swift

Lines changed: 4 additions & 4 deletions
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

Lines changed: 4 additions & 4 deletions
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)