Mohamed Mohamed Mohamed Mohamed - 6 months ago 7
Swift Question

Swift: Make sure no two arrays are the same

I'm randomly creating for different arrays with 4 random numbers (1-4) randomly. But how do I make sure that no two arrays are the same?

For example: [1,2,3,4], [4,3,2,1], [1,2,2,1], [1,2,3,4] <- first and last were generated the same randomly, how can i check to see if it's random and if it is generate it again, and if it's not, continue?

This is my code but i don't think it's working because a couple of times i'll see two of the same arrays...

func randomNumbersArray(i: UInt32) -> [Int] {
let r = [Int(arc4random_uniform(i) + 1),
Int(arc4random_uniform(i) + 1),
Int(arc4random_uniform(i) + 1),
Int(arc4random_uniform(i) + 1)]
return r
}

func arrays() {
let main = randomNumbersArray(4)
qArray = main
aArray = main
bArray = randomNumbersArray(4)
cArray = randomNumbersArray(4)
dArray = randomNumbersArray(4)

if aArray == bArray || aArray == cArray || aArray == dArray ||
bArray == cArray || bArray == dArray || cArray == dArray {
bArray = randomNumbersArray(4)
cArray = randomNumbersArray(4)
dArray = randomNumbersArray(4)
}
print(aArray)
print(bArray)
print(cArray)
print(dArray)
}

Answer

Something like this should do it:

func randomNumbersArray(i: UInt32) -> [Int] {
    let r = [Int(arc4random_uniform(i) + 1),
             Int(arc4random_uniform(i) + 1),
             Int(arc4random_uniform(i) + 1),
             Int(arc4random_uniform(i) + 1)]
    return r
}

func arrays() {
    var randArrays = [[Int]]()

    repeat {
        let newArray = randomNumbersArray(4)

        if !randArrays.contains{ $0 == newArray } {
            randArrays.append(newArray)
        }
    } while randArrays.count < 4

    //...
}
Comments