0

I have a function "randomFromZero" and another func "randomized". We need to shuffle array elements in random order. Can you help me with it?

import Foundation
func randomFromZero(to number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomized(_ array: [Int]) -> [Int] {
    var randomArray: [Int] = []
    var randomItem: Int
    for index in 0..<array.count {
        randomItem = array[randomFromZero(to: array.count)]
        randomArray.append(array[randomItem])
        array.remove(at: randomItem)
    }
    return randomArray
}
randomized([2, 3, 4, 5, 6])

Now I got error:

cannot use mutating member on immutable value: 'array' is a 'let' constant array.remove(at: randomItem)

How can I solve it?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • The array parameter is a constant. You have to make a copy of it in a local variable if you want to shuffle it. But I'd suggest you refer to the shuffling algorithms in the linked answer, as they offer ways on how to do this properly. – Rob Nov 26 '17 at 09:51
  • The main point of this question is a duplicate, however, there are other errors in the OP's code - notably that he is confusing the index into the array with the value at that index in `randomArray.append(array[randomItem])` – Grimxn Nov 26 '17 at 09:56
  • Thank you for comment, Rob! Your answer exactly what i need. I will try to do it with a local variable. Algorithms are good, but not at my point. – Alex Mats Nov 26 '17 at 10:00
  • @Grimxn - Yep, that's another bug in this code, that he would have realized that as soon as he fixed the mutable array problem. – Rob Nov 26 '17 at 11:27

0 Answers0