【问题标题】:Check for duplicates (random numbers) [duplicate]检查重复项(随机数)[重复]
【发布时间】:2016-10-12 13:51:50
【问题描述】:

在我的代码中,我生成了 1-5 之间的六个随机数。

RandomNumber1 = arc4random_uniform(5) + 1
RandomNumber2 = arc4random_uniform(5) + 1
RandomNumber3 = arc4random_uniform(5) + 1
RandomNumber4 = arc4random_uniform(5) + 1
RandomNumber5 = arc4random_uniform(5) + 1
RandomNumber6 = arc4random_uniform(5) + 1

有了这些数字,我想检查有多少重复项。两种情况:如果有 5 个不同的数字,我想执行一个代码,如果没有,我想执行另一个代码。示例;

1, 2, 3, 4, 5, 5

这里有 5 个不同的数字(只有一对)

1, 1, 2, 2, 3, 4

这里不是 5 个不同的数字(两对)

【问题讨论】:

    标签: swift swift2 int arc4random


    【解决方案1】:

    创建一个Set 并使用它来计算唯一值:

    if Set([RandomNumber1,RandomNumber2, RandomNumber3, RandomNumber4, RandomNumber5, RandomNumber6]).count == 5 {
        print("five")
    } else {
        print("not five")
    }
    

    【讨论】:

    • 似乎它对我来说并不完美,即使只有 4 个唯一值它也会执行代码。知道发生了什么吗?
    • 自己发现的,需要再问一个问题。谢谢;-)
    猜你喜欢
    • 2016-04-13
    • 2019-04-28
    • 1970-01-01
    • 2017-09-15
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2017-05-20
    相关资源
    最近更新 更多