-1

I have this code:

import UIKit

class ViewController: UIViewController {
    @IBAction func geraNumeros(_ sender: Any) {
        var numeroAleatorio:[Int] = []

        for _ in 1...6 {
            numeroAleatorio.append(Int(arc4random_uniform(60)+1))
        }

        numeroAleatorio.sort()

        labelNumeros.text = "\(numeroAleatorio[0]) - \(numeroAleatorio[1]) - \(numeroAleatorio[2]) - \(numeroAleatorio[3]) - \(numeroAleatorio[4]) - \(numeroAleatorio[5]) "

    }

    @IBOutlet weak var labelNumeros: UILabel!
}

But sometimes numbers repeating, like:

10 - 18 - 12 - 10 - 30 - 60

Like 10-10, so what to do?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Sometimes randomly generated numbers repeat. Consider when you throw a dice; you're not guaranteed a different number each time. –  Jul 11 '17 at 18:54
  • https://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift might be what you are looking for. – Martin R Jul 11 '17 at 18:55
  • Or this: https://stackoverflow.com/questions/27541145/how-to-generate-a-random-number-in-swift-without-repeating-the-previous-random-n. – Martin R Jul 11 '17 at 19:00
  • @FelipeRibeiro https://www.dropbox.com/s/0zu5a6r0zdde99o/Sena%20Combination%20Generator.zip?dl=1 – Leo Dabus Jul 11 '17 at 21:17

1 Answers1

0

Before appending the value to your array, check if it is already present in your array using the .contains() function. If it exists, continue the loop until we have the 6 elements we need.

For this to work you must change your loop to keep looping until 6 valid elements are found.

Something like

while numeroAleatorio.count < 6
Daniel
  • 10,641
  • 12
  • 47
  • 85