Skip to content

Instantly share code, notes, and snippets.

@minhwang
Last active November 22, 2016 09:32
Show Gist options
  • Save minhwang/0318f2e6b8baa8130666d5895a33b51c to your computer and use it in GitHub Desktop.
Save minhwang/0318f2e6b8baa8130666d5895a33b51c to your computer and use it in GitHub Desktop.
How to pick numbers randomly from array
//: Playground - noun: a place where people can play
import UIKit
func pickNumbersRandomly(from numbers: [UInt], theNumberOf: UInt) -> [UInt] {
var numbers = numbers
var numbersPickedRandomly = [UInt]()
for _ in 1...theNumberOf {
let indexPickedRandomly = Int(arc4random_uniform(UInt32(numbers.count)))
let numberPicked = numbers[indexPickedRandomly]
numbersPickedRandomly.append(numberPicked)
numbers.remove(at: indexPickedRandomly)
}
return numbersPickedRandomly.sorted()
}
var numbers: [UInt] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
print(pickNumbersRandomly(from: numbers, theNumberOf: 6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment