vendredi 4 novembre 2016

Unique random number generation in Swift

In the process of learning Swift, I'm building a lotto numbers generator that generates a random number and appends it into an array, if the number already exists then it should re-generate a random numbers and append that one to the array.

I've come up with this. I want to be able to have a reusable class where I can decide how many numbers I want it to generate.

How would you guys solve this in a simpler way?

class EuroMillions {

var randomNumber:Int = 0
var numberArray = [Int]()

func generateRandomNumber (numbers: Int, repetitions: Int) -> (Int, Int, Int) {

    for number in 1...6 {
        randomNumber = Int(arc4random_uniform(UInt32(numbers)))
        checkArray(numbers: numbers)
    }
    return (randomNumber, numbers, repetitions)

}

func checkArray(numbers: Int) {
    if numberArray.contains(randomNumber){
        //re-generate
        print("Number \(randomNumber) exists!")
        randomNumber = Int(arc4random_uniform(UInt32(numbers)))
        checkArray(numbers: numbers)

        print("Replacing it with \(randomNumber)")
    } else {
        numberArray.append(randomNumber)
    }
  }
 }
}

let firstNumbers = EuroMillions()
firstNumbers.generateRandomNumber(numbers: 50, repetitions: 6)
let finalNumbers = firstNumbers.numberArray
print(finalNumbers)




Aucun commentaire:

Enregistrer un commentaire