Making four separate variables

左心房为你撑大大i 提交于 2019-12-11 02:57:26

问题


I am trying to make four separate variables that are all different so that a and b are different, a and c are different, b and c are different and so on so forth. Here are the four variables.

var a = Int(arc4random_uniform(5))
var b = Int(arc4random_uniform(5))
var c = Int(arc4random_uniform(5))
var d = Int(arc4random_uniform(5))

回答1:


let a = Int(arc4random_uniform(5))
var b = Int(arc4random_uniform(5))
while b == a {
    b = Int(arc4random_uniform(5))
}
var c = Int(arc4random_uniform(5))
while c == a || c == b {
    c = Int(arc4random_uniform(5))
}
var d = Int(arc4random_uniform(5))
while d == c || d == b || d == a {
    d = Int(arc4random_uniform(5))
}
println(a)  // 2
println(b)  // 0
println(c)  // 4
println(d)  // 3



回答2:


Even though the question has been already answered, here is an alternative solution:

var set = Set<UInt32>()

while set.count < 4 {
    set.insert(arc4random_uniform(5))
}


来源:https://stackoverflow.com/questions/31353355/making-four-separate-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!