Skip to content

Instantly share code, notes, and snippets.

@swift-student
Last active March 18, 2020 15:40
Show Gist options
  • Save swift-student/48cbc4dfc3b43ce97ed2b41e038b0287 to your computer and use it in GitHub Desktop.
Save swift-student/48cbc4dfc3b43ce97ed2b41e038b0287 to your computer and use it in GitHub Desktop.

Since we are going to be shuffling the array in place, I will be using an inout parameter. I am not sure I would understand how to do a truly uniform shuffle, as my math skills are not stellar. Instead I will iterate through the array and select another element at random to replace each element. If I have time, I will then attempt to implement arc4random_uniform() instead of using random.

var arrayToShuffle = [6,7,8,9]

func randomShuffle<T>(_ array: inout Array<T>) {
    for index in 0...array.count - 1 {
        let swapIndex = Int.random(in: 0...array.count - 1)
        array.swapAt(index, swapIndex)
    }
}

randomShuffle(&arrayToShuffle)
print(arrayToShuffle) // [6, 9, 7, 8]
randomShuffle(&arrayToShuffle)
print(arrayToShuffle) // [8, 6, 7, 9]
randomShuffle(&arrayToShuffle)
print(arrayToShuffle) // [6, 9, 8, 7]

Above is my first pass at it. I made it take any type of array through use of a generic, T. As stated above it simply loops through each element and swaps it with another random element. It seems to me as this would lead to a fairly uniformly random shuffle, but I am not good with probability.

Now I have swapped out random for arc4random_uniform, and switched to strings to show that it works with arrays with any element type. Also, I am forgoing using .swapAtIndex, and instead am using a method I had learned previously to swap two variables using the format (a, b) = (b, a).

var arrayToShuffle = ["hey","how","are","you"]

func randomShuffle<T>(_ array: inout Array<T>) {
    for index in 0...array.count - 1 {
        let swapIndex = Int(arc4random_uniform(UInt32(array.count - 1)))
        (array[index], array[swapIndex]) = (array[swapIndex], array[index])
    }
}

randomShuffle(&arrayToShuffle)
print(arrayToShuffle) // ["how", "are", "you", "hey"]
randomShuffle(&arrayToShuffle)
print(arrayToShuffle) // ["are", "you", "hey", "how"]
randomShuffle(&arrayToShuffle)
print(arrayToShuffle) // ["are", "how", "hey", "you"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment