arrays - If 语句查找重复值?

标签 arrays swift

好吧,假设我有一个随机生成值的列表,有时它会生成两次相同的值。

例如生成的 int 值:

1, 1, 2, 3, 4

然后我有一个名为 duplicateTracker() 的方法,它的工作是在列表中查找重复项。

我有一个想法,它应该使用 if else 语句来完成。因此,如果它检测到重复数字,则为真,否则为假。

我该怎么做?

最佳答案

这使用了 Foundation 方法,但考虑到您的用例,您可能需要考虑让我们使用 NSCountedSet跟踪您生成的号码。例如

let numbersGenerator = AnyIterator { return 1 + arc4random_uniform(10) }
var numbersBag = NSCountedSet()

for num in (0...15).flatMap({ _ in numbersGenerator.next()}) {
    print(num, terminator: " ")
    numbersBag.add(num)
} /* 1 3 2 2 10 1 10 7 10 6 8 3 8 10 7 4 */
print()

numbersBag.forEach { print($0, numbersBag.count(for: $0)) }
/* 1 2
   2 2
   3 2
   4 1
   6 1
   7 2
   8 2
   10 4 */

由于 NSCountedSet 符合 Sequence,您可以轻松提取您希望使用的任何“重复诊断”,例如过滤器:

print("Numbers with duplicates: ", numbersBag.filter { numbersBag.count(for: $0) > 1 })
// Numbers with duplicates: [1, 2, 3, 7, 8, 10]

关于arrays - If 语句查找重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999068/

相关文章:

python - 将 pandas DataFrame 转换为没有额外列的记录数组

JavaScript 效率 - 'forEach' 具有多个 'if' 或 'if' 只允许 'forEach'

ios - Realm 。更新多个ViewController中的数据

ios - UITableViewDelegate 方法的确切顺序是什么 - 奇怪的行为

swift - 访问相机时 ios 10 应用程序崩溃

swift - 如何在不创建无限循环的情况下让 RxSwift 中的主题将值推送给自身

java - char 数组中出现意外字符

python - 屏蔽数组索引问题

Python C 扩展以负步长读取 numpy 数组

ios - Swift 仅在首次使用导航 Controller 启动时显示 View