0

I'm creating an app that uses an array of 25 labels. I want these labels to be assigned random numbers between 1 and 25 that don't get repeated. I can figure out how to assign these labels to random numbers between 1 and 25 that can be repeated, but I can't figure out how to not have these numbers repeat. My code so far is below.

 for label in labelsArray {
     let randomNumber = (arc4random() % 25) + 1
      label.text = "\(randomNumber)"

Is it possible to have each of the labels assigned to a different number between 1 and 25?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Msutton
  • 3
  • 2

2 Answers2

0

Instead of generating 25 random numbers, start with an array of the numbers 1...25 and shuffle the array randomly.

(Actually in this particular case you could just start with an array of the 25 labels, shuffle the array, and then assign them the numbers in order.)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Does this work with an array of labels? Sorry, I'm new to Swift and I'm not very good when it comes to arrays. – Msutton Dec 05 '15 at 23:48
0

Start with an array of 1...25 and pull the numbers out of it as you choose them:

var a = Array(1...25)

for label in labelsArray {
    let index = Int(arc4random_uniform(UInt32(a.count)))
    let randomNumber = a[index]
    a.removeAtIndex(index)
    label.text = "\(randomNumber)"
}
vacawama
  • 150,663
  • 30
  • 266
  • 294