Hi all,
Shuffling an array means randomly re-arranging the content of an array .Shuffling algorithm can be used in many places now days like in card games, music player , media player etc.
Shuffling of an array can be done in two ways.
- Using GameplayKit framework but it is only for iOS 9.0 or above. For Example:-
let unShuffledArray = [Int](1...100)
var arr:AnyObject = [0,0]
if #available(iOS 9.0, *) {
arr = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(unShuffledArray)
}
print(unShuffledArray)
print(arr)
- Using native code function.For Example:-
func convertToShuffledArray<T>(var array: Array<T>) -> Array<T>
{
for var index = array.count - 1; index > 0; index--
{
let j = Int(arc4random_uniform(UInt32(index-1)))
swap(&array[index], &array[j])
}
return array
}
an above function can be used as following:-
let unShuffledArray = [Int](1...100)
print("strings: \(convertToShuffledArray(unShuffledArray))")
Thanks for reading.
0 Comment(s)