1

I want to return random number from the range of number. The return number will be only once until all the number will be return.

I am using following code to generate random number, but extra i have to do to get number only once?

Function:

    func randomNumber(range: Range<Int> = 1...3) -> Int {
     let min = range.startIndex
     let max = range.endIndex
     return Int(arc4random_uniform(UInt32(max - min))) + min
    } 

Calling:

    var ran = randomNumber(0...36)

Output:

ran: 30
ran: 16
ran: 0
ran: 14
ran: 18
ran: 7
ran: 20
ran: 13
ran: 26
ran: 26
ran: 3
ran: 12
ran: 35
ran: 27
ran: 0
ran: 5
ran: 5
ran: 3

Please suggest me what changes to be done.

Suraj Sonawane
  • 2,044
  • 1
  • 14
  • 24

1 Answers1

1

This function creates an array with all of the numbers from 0 to the max (36 in your case). Then it makes a copy of the array and gets a random index from the copied array. When that number is picked, it is removed from the copied array. Repeat as many times as there are numbers in the original array.

func random(max: Int) {

    var numbers = [Int]()
    for x in 0...max {
        numbers.append(x)
    }

    var numbersCopy = numbers
    for _ in 0..<numbers.count {
        let randomIndex = Int(arc4random_uniform(UInt32(numbersCopy.count)))
        let result = numbersCopy.removeAtIndex(randomIndex)
        print("Random Number: \(result)")
    }
}
cuomo456
  • 185
  • 7