PictureMeAndYou - 11 months ago 90

Swift Question

I know there is a new shuffle method with **iOS 9**

but I am wondering if there is anyway to shuffle two arrays the same way?

For example

`[1,2,3,4] and [a,b,c,d]`

shuffle

[3,4,1,2] and [c,d,a,b]

Answer Source

Using the `shuffle()`

method from How do I shuffle an array in Swift? and the ideas from How can I sort multiple arrays based on the sorted order of another array
you can shuffle the array *indices* and then re-order both (or more)
arrays accordingly:

```
let a = [1, 2, 3, 4]
let b = ["a", "b", "c", "d"]
var shuffled_indices = a.indices.shuffle()
let shuffled_a = Array(PermutationGenerator(elements: a, indices: shuffled_indices))
let shuffled_b = Array(PermutationGenerator(elements: b, indices: shuffled_indices))
print(shuffled_a) // [3, 1, 2, 4]
print(shuffled_b) // ["c", "a", "b", "d"]
```

**Update for Swift 3 (Xcode 8):** `PermutationGenerator`

does not
exist in Swift 3 anymore.
Using the `shuffled()`

method
from Shuffle array swift 3 the same can be achieved with

```
var shuffled_indices = a.indices.shuffled()
let shuffled_a = shuffled_indices.map { a[$0] }
let shuffled_b = shuffled_indices.map { b[$0] }
```