Search code examples
iosswiftarc4random

iOS Programming: Making an arc4_random not repeat itself using a do while loop


In this code 2nd line goes through the array and output what it receives and its random. But sometimes I get the same thing twice, like it would say "Straub", and then "Straub" and then something else like "Rusher". I've tried to do a "do while loop" but I don't know how to set it up where it doesn't repeat itself. By the way this the swift programming language.

let types = ["Alex", "Straub", "Rusher", "Graser"]

let type = types[Int(arc4random_uniform(UInt32(types.count)))]

println(type)

If you have any questions please post them in the comments section


Solution

  • This avoids a direct repetition:

    var lastIndex = -1
    var index = -1
    
    let types = ["Alex", "Straub", "Rusher", "Graser"]
    
    do {
        index = Int(arc4random_uniform(UInt32(types.count)))
    } while index == lastIndex
    
    println(types[index])
    lastIndex = index