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, thewhile
loop will never exit. It's very unlike tho.Another approach is to create mutable copy of original array and then exclude picked items:
By removing your picked value from array, prevent's from duplicates to be picked
You can do it like this:
A
set
can contain unique elements only, so it can't have the same element more than once.I created an empty
set
, then as long as the array contains less than 5 elements (the number you chose), I iterated and added a random element to theset
.In the last step, we need to convert the set to an array to get the array that you want.
If you don't care about changing the original array, the following code will put the picked elements at the end of the array and then it will return the last part of the array as a slice. This is useful if you don't care about changing the original array, the advantage is that it doesn't use extra memory, and you can call it several times on the same array.
Example: