Swift5

How can I stop random numbers appearing consecutively?

Can you give an example of what you mean?

I understand you generate random numbers and you get the same several times ?

What type of random ? Are they Int ?

If I understand your point, you could save the random generated in an array. And each time you draw for a new random, test if it's already in the array, if so repeat the draw. Take care if there is no possibility left (if you call [1...10].random() for instance), not to go in indefinite loop.

If you just want the new number be different from the last draw, keep lastValue instead of an array of Int.

Here are some sample code:

var validDraws : [Int] = []
var allDraws : [Int] = []
let deck = Array(1..<100)
for _ in 1...50 {
    let x = deck.randomElement()!
    allDraws.append(x)
    if !validDraws.contains(x) {
        validDraws.append(x)
    }
}

print(allDraws)
print(validDraws)

Which gives:

[57, 24, 81, 69, 11, 97, 6, 64, 98, 77, 3, 54, 70, 76, 93, 52, 7, 71, 86, 5, 14, 87, 31, 80, 35, 18, 67, 32, 4, 64, 28, 53, 14, 16, 46, 29, 69, 63, 98, 23, 45, 68, 20, 56, 87, 19, 13, 95, 65, 27]

[57, 24, 81, 69, 11, 97, 6, 64, 98, 77, 3, 54, 70, 76, 93, 52, 7, 71, 86, 5, 14, 87, 31, 80, 35, 18, 67, 32, 4, 28, 53, 16, 46, 29, 63, 23, 45, 68, 20, 56, 19, 13, 95, 65, 27]

Swift5
 
 
Q