【问题标题】:Generate random numbers and check for duplicates生成随机数并检查重复项
【发布时间】:2016-04-13 00:01:34
【问题描述】:

我想知道是否有一种简单的方法可以检查六个不同随机数之间的重复项。我想检查 6 个随机数中的 4 个以上是否相同以创建 if 语句。

例如;

let firstRandomNumber = arc4random_uniform(3) + 1
let secondRandomNumber = arc4random_uniform(3) + 1
let thirdRandomNumber = arc4random_uniform(3) + 1
let fourthRandomNumber = arc4random_uniform(3) + 1
let fifthRandomNumber = arc4random_uniform(3) + 1
let sixthRandomNumber = arc4random_uniform(3) + 1

使用这些随机数,如果其中四个或更多相同(例如3, 3, 3, 3, 2, 1),我想执行和操作。有人知道怎么做吗?

【问题讨论】:

  • more than four duplicates 是什么意思?给我一个输入和输出的例子。例如。这个输入 [3, 3, 2, 2, 1, 2] 应该确定什么输出?
  • 如果,例如,[3, 3, 3, 3, 2, 1] - 如果六个随机生成的数字中有四个相同
  • 好的。您想知道相同的数字是否至少出现 4 次。谢谢。
  • @appzYourLife 是的,感谢您注意到我的错误解释。 :-)

标签: swift duplicates


【解决方案1】:

这里有一个更简短的解决方案:

let numbers      = [3, 3, 2, 3, 2, 3]

let counts       = numbers.map({ (N) in numbers.filter({ $0 == N }).count })
let fourOrMore   = counts.contains({ $0 >= 4 })

if fourOrMore  { print(" there are more than four identical values") }

还有一个更短的:

let numbers      = [3, 3, 2, 3, 2, 3]

if numbers.contains({ (N) in numbers.filter({$0 == N}).count >= 4 })
{ print(" there are more than four identical values") }

【讨论】:

    【解决方案2】:

    这个呢

    let allValues = [firstRandomNumber,secondRandomNumber, thirdRandomNumber, fourthRandomNumber,fifthRandomNumber, sixthRandomNumber]
    
    let maxOccurrencies:(value:UInt32, times:Int)? = allValues
        .reduce([UInt32:Int]()) { (var dict, elm) -> [UInt32:Int] in
            dict[elm] = (dict[elm] ?? 0) + 1
            return dict
        }
        .maxElement { $0.1 < $1.1 }
    
    
    if let (value, times) = maxOccurrencies where times >= 4 {
        print("The value \(value) does appear \(times) times")
    }
    

    【讨论】:

    • 完美运行!感激不尽,像你这样的人是最棒的!
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2012-12-17
    相关资源
    最近更新 更多