Randomly select 5 items from a table list without repeating an item

advertisements

I am currently trying to make an app for iOS but I can't get some simple code down. Basically I need to randomly select 5 elements from an array list without repeating an element. I have a rough draft, but it only displays one element.

Here is my code:

let array1 = ["salmon", "turkey", "salad", "curry", "sushi", "pizza"]

let randomIndex1 = Int(arc4random_uniform(UInt32(array1.count)))

print(array1[randomIndex1])


Just my ¢2: Moe Abdul-Hameed's solution has one theoretical drawback: if you roll the same randomIndex in every iteration, the while loop will never exit. It's very unlike tho.

Another approach is to create mutable copy of original array and then exclude picked items:

var source = array1
var dest = [String]()
for _ in 1...5 {
    let randomIndex = Int(arc4random_uniform(UInt32(source.count)))
    dest.append(source[randomIndex])
    source.remove(at: randomIndex)
}

print(dest)