Given a task - write a function for shuffle array. Let's start from simple solution. This method called Pencil and paper method
Example of function which shuffle array
Function shuffle, that provided below, works by following algorithm:
Example of extension for shuffle array
The algorithm remains the same. But for now, because we use extension, any array can be shuffled, as we can see above now we can shuffle array of strings too.
Mutating self extension method
We can add modified version of our extension which modify current array in-place without return new array.
Example of extension which shuffle current array in-place
Example of shuffle function implemented modern algorithm
Generic function
We also can make our function generic and apply it to array of any type, for example for array of strings.
Example of generic implementation
Also let's create two extensions as before: 1) will return new shuffled array 2) will shuffle array in-place
Example of extension with modern shuffle algorithm (Immutable and In-place)
Example of function which shuffle array
Function shuffle, that provided below, works by following algorithm:
- Make copy of incoming array to variable arrayCopy (we will remove items from this copy)
- Make new empty array randomArray(we will add new values to this array)
- For each item in copied array
- Generate random index from 0 to arrayCopy length
- Remove item with random index from arrayCopy (when remove we can store removed item)
- Add removed item to randomArray
- Return randomArray
Making Extension for shuffle array
For more handy usage let's move this code to extensionExample of extension for shuffle array
The algorithm remains the same. But for now, because we use extension, any array can be shuffled, as we can see above now we can shuffle array of strings too.
Mutating self extension method
We can add modified version of our extension which modify current array in-place without return new array.
Example of extension which shuffle current array in-place
Complexity of Pencil and paper algorithm
Complexity of this algorithm will be O(nˆ2) because- O(n) is for one 'for loop'
- O(n) is for removing from array
Model Shuffle Algorithm
How we can improve time complexity of shuffling? There is Modern method which allow us to get linear O(n) complexity. It is because we have only one loop over the array and swap random item on each iteration.
Example of shuffle function implemented modern algorithm
Generic function
We also can make our function generic and apply it to array of any type, for example for array of strings.
Example of generic implementation
Also let's create two extensions as before: 1) will return new shuffled array 2) will shuffle array in-place
Example of extension with modern shuffle algorithm (Immutable and In-place)