0

I'm relatively new to swift and now I'm simply playing around and learning. I have an array of strings and I'm using arc4random_uniform to print these lines of text. But I can't seem to figure out how to exclude the already picked ones from being picked repeatedly. At least until all the rest have been picked. What I've got:

let array1 = ["pizza", "carrot", "fish", "monkey", "window"]

let pickOfArray = Int(arc4random_uniform(4))

print (array1[pickOfArray])
jlsiewert
  • 3,494
  • 18
  • 41
Alvarsson
  • 115
  • 3
  • 7
  • What you want is non-repeating random numbers. From this question: https://stackoverflow.com/questions/1617630/non-repeating-random-numbers the best solution is actually shuffling – Marmoy Jul 14 '17 at 12:30

3 Answers3

0

Create second array of picked indexes and change your code to:

  1. Generate random index
  2. Check if your random index is inside pickedIndexes array
  3. If false proceed to point 4, if true check if pickedIndexes.count is the same as array1, if yes then reset pickedIndexed and proceed to next point, else back to point 1
  4. Append your number to pickedIndexes and get your value from array1
Michał Kwiecień
  • 2,734
  • 1
  • 20
  • 23
0
  1. Create 2 arrays
  2. Fill one array with all possible values

  3. if array1 not empty { array2.append( array1.remove(at: randomIndex)) } else { swap arrays }

  4. repeat 3

Basically put all values you have used from array 1 and put them in array 2 untill you used all values from array 1. Then repeat the other way around (or put all values back in array 1 whatever.

Simon
  • 2,419
  • 2
  • 18
  • 30
  • Hey and thanks! I think I get it but I'm stuck at the last part where the second array is full and I need to put them back into array 1 again. How do I put all the strings back into the first array? – Alvarsson Jul 15 '17 at 10:25
  • Multiple possibilities, you can for example do something like array1 = array2, empty array 2. – Simon Jul 17 '17 at 14:27
0

Another option, if you are okay with mutating the original Array, is to just remove elements as you use them:

var array1 = ["pizza","carrot","fish","monkey","window"]

while array1.count > 0 {
    let pickOfArray = array1.remove(at: Int(arc4random_uniform(UInt32(array1.count))))
    print(pickOfArray)
}