Skip to content

Commit 345f844

Browse files
authored
add SelectionSamplingExample.swift
1 parent 12b0bdb commit 345f844

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//
2+
// Select.swift
3+
//
4+
//
5+
// Created by Cheer on 2017/3/9.
6+
//
7+
//
8+
9+
import Foundation
10+
11+
func select<T>(from a: [T], count requested: Int) -> [T] {
12+
13+
// if requested > a.count, will throw ==> fatal error: Index out of range
14+
15+
if requested < a.count {
16+
var arr = a
17+
for i in 0..<requested {
18+
19+
//arc4random_uniform(n) ==> the range is [0...n-1]
20+
//So: arc4random_uniform(UInt32(arr.count - i - 2)) + (i + 1) ==> [0...arr.count - (i + 1) - 1] + (i + 1) ==> the range is [(i + 1)...arr.count - 1]
21+
//Why start index is "(i + 1)"? Because in "swap(&A,&B)", if A's index == B's index, will throw a error: "swapping a ___location with itself is not supported"
22+
23+
let nextIndex = Int(arc4random_uniform(UInt32(arr.count - i - 2))) + (i + 1)
24+
swap(&arr[nextIndex], &arr[i])
25+
}
26+
return Array(arr[0..<requested])
27+
}
28+
29+
if requested == a.count { return a }
30+
31+
return [T]()
32+
}

0 commit comments

Comments
 (0)