2

I have an array of book titles, and another with corresponding book authors. Let's just assume I need them in separate arrays as opposed to the same dictionary. How can I reorder the indexes of both arrays, while making sure the index of array 2 still corresponds to the index of array 1?

//This is what I currently have:
var arrayOne = ["one", "two", "three", "four"]
var arrayTwo = [1, 2, 3, 4]

//The new indexes should be random, non-repeating integers
arrayOne = ["four", "two", "three", "one"]
arrayTwo = [4, 2, 3, 1]
slider
  • 2,736
  • 4
  • 33
  • 69

1 Answers1

1

This code is tested on Swift 2.0

    extension CollectionType {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    }
}

extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        if count < 2 { return }

        for i in 0..<count - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

let arr1 = [1, 2, 3, 4]
let arr2 = ["a", "b", "c", "d"]

var shuffled_ind = arr1.indices.shuffle()

let shuffled_arr1 = Array(PermutationGenerator(elements: arr1, indices: shuffled_ind))
let shuffled_arr2 = Array(PermutationGenerator(elements: arr2, indices: shuffled_ind))

print(shuffled_arr1) // [3, 1, 2, 4]
print(shuffled_arr2) // ["c", "a", "b", "d"]

HERE IS THE OUTPUT

OUTPUT

Took Reference from this two post and used their extention

How do I shuffle an array in Swift?

How can I sort multiple arrays based on the sorted order of another array3

Randomize two arrays the same way Swift

Community
  • 1
  • 1
O-mkar
  • 5,430
  • 8
  • 37
  • 61