Created
November 20, 2015 22:28
-
-
Save possen/4e0119c103c174af724c to your computer and use it in GitHub Desktop.
RandomArrays: pick randomly to build new array in two different ways
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Description: RandomArrays: pick randomly to build new array in two different ways. One a shuffle the other | |
// picking from the array. Shuffle uses Fischer-Yates algorithm to generate uniform randomness. Allthough it | |
// might be better to use Apple's Game kit function GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(array) | |
// if available in the OS release. Also this only works on arrays, if you want to shuffle any colletion type | |
// it is possible to extend MutableCollectionType. | |
// | |
// Author: Paul Ossenbruggen | |
// | |
// Date: Nov 20, 2015 | |
// Language: Swift | |
// | |
import Foundation | |
// picks only numbers from array may pick same values over and over. | |
let array = [10, 4, 2, 5, 6, 3, 1, 14, 11, 15] | |
print(array.map { _ in | |
return array[Int(arc4random_uniform(UInt32(array.count)))] | |
}) | |
func shuffleArray(var array : [Int]) -> [Int] { | |
for (index, _) in array[0..<array.count-1].enumerate() { | |
let randomIndex = Int(arc4random_uniform(UInt32(array.count - index))) + index | |
guard index != randomIndex else { continue } // swap does not like it if you swap same indexes | |
swap(&array[index], &array[randomIndex]) | |
} | |
return array | |
} | |
print(shuffleArray(array)) | |
print(array) // swift does not change original array. | |
func shuffleArrayInPlace(inout array : [Int]) { | |
for (index, _) in array[0..<array.count-1].enumerate() { | |
let randomIndex = Int(arc4random_uniform(UInt32(array.count - index))) + index | |
guard index != randomIndex else { continue } // swap does not like it if you swap same indexes | |
swap(&array[index], &array[randomIndex]) | |
} | |
} | |
var newArray = array | |
shuffleArrayInPlace(&newArray) | |
print(newArray) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment