【问题标题】:How to count 2 different duplicate values in array - Swift如何计算数组中的 2 个不同的重复值 - Swift
【发布时间】:2015-08-24 08:39:44
【问题描述】:

我正在创建一个测验,我有一个布尔数组,我正在尝试找到一种方法来计算有多少“真”和“假”值,这样我就可以向用户展示测验的结果.我想将结果存储在一个变量中,以便稍后调用。

我查看了 set 集合类型,但似乎无法理解它。我是否将 initalise 设置为布尔值?

answersArray = [true, false, true, false, true, false, true]

trueAnswersCount = set<Bool>()

【问题讨论】:

    标签: arrays swift set boolean


    【解决方案1】:
        var wordCounts = [String: Int]()
        var allWords = ["this","is","a","test","this","is", "another", "test"]
        for word in allWords {
           if wordCounts[word] == nil {
              wordCounts[word] = 1
           } else {
              wordCounts[word]! += 1
           }
         }
    
        print(wordCounts) // prints: ["a": 1, "this": 2, "test": 2, "another": 1, "is": 2]
        print(wordCounts["this"]!) // get the count of word "this": 2
        allWords = Array(wordCounts.keys) // remove duplicates
    

    甚至更快:

        var wordCounts: NSCountedSet!
        var allWords = [true, true, false, false, false, false, true, false] as [Any]
    
        wordCounts = NSCountedSet(array: allWords)
        print(wordCounts.count(for: true)) // print: 3
    

    see details here

    【讨论】:

      【解决方案2】:

      您可以创建一个函数,该函数接受 SequenceType 和一个值并返回提供的值与序列中的元素匹配的次数:

      func countMatches<Seq: SequenceType where Seq.Generator.Element: Equatable> 
                       (arr: Seq, v: Seq.Generator.Element) -> Int {
      
          return arr.reduce(0) {
              if $1 == v { return $0 + 1 }
              return $0
          }
      }
      
      let answersArray = [true, false, true, false, true, false, true]
      countMatches(answersArray, true)  // 4
      countMatches(answersArray, false) // 3
      

      或者,对于 Swift 2:

      extension SequenceType where Generator.Element: Equatable {
          func countMatches(v: Generator.Element) -> Int {
              return reduce(0) { 
                  if $1 == v { return $0 + 1 }
                  return $0
              }
          }
      }
      
      let answersArray = [true, false, true, false, true, false, true]
      answersArray.countMatches(true)  // 4
      answersArray.countMatches(false) // 3
      

      【讨论】:

      • Swift 1.2 not 需要空参数名_ .
      • 除非我弄错了,否则 Xcode 6.3 (Swift 1.2) 和 Xcode 7 (Swift 2) 之间发生了变化。
      • 我的错,你是对的;我在编写第一个函数时使用的是 Swift 2。
      【解决方案3】:

      您可以轻松地使用 Swift 的函数式编程能力为您的问题获得非常简洁的解决方案:

      let trueAnswersCount = answersArray.filter{$0 == true}.count
      

      【讨论】:

        【解决方案4】:

        为什么不直接使用filter()

        answersArray = [true, false, true, false, true, false, true]
        
        let trueCount  = answersArray.filter { $0 == true }.count
        let falseCount = answersArray.filter { $0 == false }.count
        

        【讨论】:

          【解决方案5】:

          您不能只使用本机 Set 类型,因为 Set 不包含重复值。例如,以下将发出{false, true}

          let answersArray = [true, false, true, false, true, false, true]
          let trueAnswersCount = Set<Bool>(answersArray)
          

          如果您愿意使用 Cocoa Touch 中的类,NSCountedSet 可以大大简化这一点。

          let answersArray = [true, false, true, false, true, false, true]
          
          let countedSet = NSCountedSet()
          countedSet.addObjectsFromArray(answersArray)
          
          countedSet.countForObject(false) // 3
          countedSet.countForObject(true) // 4
          

          NSCountedSet 仍然是一个 Set 并且只存储唯一值,但它还会跟踪每个唯一元素被添加到其中的次数。

          【讨论】:

            【解决方案6】:

            您可以简单地遍历您的数组,并在每次值为 true 时加一。

            这是一个简单的例子:

            var answersArray : [Bool]
            
            answersArray = [true, false, true, false, true, false, true]
            
            var nbTrueAnswers : Int = 0
            
            for value in answersArray {
                if (value == true) {
                    nbTrueAnswers++;
                }
            }
            
            println("nbTrueAnswers : \(nbTrueAnswers)")
            

            或查看:http://swiftstub.com/184888077/

            如果有帮助请告诉我:)

            【讨论】:

            • 短:let nbTrueAnswers = reduce(answersArray, 0) { $0 + Int($1) } :)
            • @MartinR 它不是更短......它是最短的:P
            猜你喜欢
            • 1970-01-01
            • 2016-03-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-11-18
            • 2021-04-09
            • 2011-07-12
            • 1970-01-01
            相关资源
            最近更新 更多