Shuffle

Fisher–Yates shuffle

func shuffle<T>(arr:[T]) ->[T]
{
    var array:[T] = arr
    var m = array.count
    var t :T
    var i = 0
   
    while (m > 0) {
       
        m -= 1
        i = Int(arc4random_uniform(UInt32(m)))
       
        t = array[m]
        array[m] = array[i]
        array[i] = t
    }
   
    return array
}

with gameplaykit
then NSArray has extended func .shuffled()

import GameplaKit
(array as NSArray).shuffled()

or with GKRandomSource
import GameplayKit

var arr = [1,2,3,4,5,6,7]

let source = GKRandomSource.sharedRandom()
source.arrayByShufflingObjects(in: arr) // [3, 7, 5, 1, 4, 2, 6]

with seed

import GameplayKit

var arr = [1,2,3,4,5,6,7]

let source = GKLinearCongruentialRandomSource()
source.seed = 12345
source.arrayByShufflingObjects(in: resultsArray)

Tags: