【问题标题】:Swift Comparison in consecutive numbers inside array and its count [duplicate]数组内连续数字的快速比较及其计数[重复]
【发布时间】:2019-04-27 20:36:59
【问题描述】:

如何比较数组中的两个连续数字并找到其计数。

let numberArray = [1,2,4,6,7,10,12,13]
// I want to compare two consecutive numbers like [1,2], [4,6], [7,10], [12,13]

例如:
首先,我想计算数组中前两个数字[1,2(difference=1)]的差异,然后是接下来的两个数字[4,6(difference=2)],然后是[7,10(difference= 3)] 和 [12,13(difference=1)] 最后。
最后,我想计算有 1 的差值。在这种情况下,计数是 2。

我应该用什么方法来做这个?

提前致谢。

【问题讨论】:

    标签: arrays swift filter


    【解决方案1】:

    通过Martin Ranswer,您可以检查如何创建对,如下所示,

    let input = [1,2,4,6,7,10,12,13]
    let output = stride(from: 0, to: input.count - 1, by: 2).map{(input[$0], input[$0 + 1])}
    

    现在您可以创建差异数组并找到如下所示的计数,

    let differences = output.map({ $0.1 - $0.0 })
    let onesCount = differences.filter({ $0 == 1}).count
    
    print(differences)
    print(onesCount)
    

    输出

    [1, 2, 3, 1]
    2
    

    【讨论】:

    • 嗨,谢谢。这就像一个魅力!这个非常简单易懂
    【解决方案2】:

    您可以通过使用zip compactMapreduce 的两行代码来实现这一点:

    首先我们创建一个连续元素的元组,我们使用zip 来使用元素的索引和compactMap 过滤nil 元素,然后我们减少新数组以仅计算具有差异的元组1

    //Create tuples of consecutive values
    let tuples = zip(numberArray.indices, numberArray).compactMap{$0 % 2 == 0 ? nil : (numberArray[$0-1],$1) }
    // reduce to count only the tuples with difference of 1
    let diffOneCount = tuples.reduce(0,{$1.0+1 == $1.1 ? $0+1 : $0})
    

    【讨论】:

      【解决方案3】:

      @Philip 的好回答。这是一个更新的解决方案,也处理了其他情况。

      let numbers = [1, 2, 5, 4, 10, 6, 7, 8, 11, 10, 23]
      var allDifference: [Int] = []
      for index in stride(from: 0, to: numbers.count, by: 2) {
         let firstValue = numbers[index]
         let secondValue = ((index == numbers.count - 1 && numbers.count % 2 != 0) ? 0 : numbers[index + 1])
         allDifference.append(abs(firstValue - secondValue))
      }
      
      let oneDifferenceCount = allDifference.filter { $0 == 1 }.count
      print("Result: ", oneDifferenceCount)
      

      【讨论】:

        【解决方案4】:

        我确信有更好的方法可以做到这一点(但现在是星期一早上)。 一种简单的解决方案是使用步幅循环遍历数组,让您可以从两步中走出来。 然后,您将每个差异附加到一个新的差异数组。 最后在这个结果数组上使用一个过滤器来确定这种差异发生的频率。

        let difference      = 1
        let array           = [1,2,4,6,7,10,12,13]
        var differenceArray = [Int]()
        for index in stride(from: 1, to: array.count, by: 2) {
            let difference  = array[index]-array[index-1]
            differenceArray.append(difference)
        }
        
        print(differenceArray.filter{ $0 == difference }.count)
        

        【讨论】:

          猜你喜欢
          • 2021-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-09
          • 2014-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多