【问题标题】:Using nested reduce in Swift在 Swift 中使用嵌套 reduce
【发布时间】:2016-12-02 17:24:20
【问题描述】:

我有一个包含Double 数组的数组,如屏幕截图所示:

我的目标是得到每个数组的 Double 元素相乘的总和。这意味着,我想将每个数组的所有元素相乘,然后,在我的情况下,我将有 3 个值,所以我得到它们的总和。

我想使用reduceflatMap?或任何优雅的解决方案。

我尝试了什么?

totalCombinations.reduce(0.0) { $0 + ($1[0]*$1[1]*$1[2])  }

但这只有在我知道包含双精度的数组的大小时才有效。

【问题讨论】:

    标签: ios arrays swift functional-programming reduce


    【解决方案1】:

    你可以这样写:

    let totalCombinations: [[Double]] = [
        [2.4,1.45,3.35],
        [2.4,1.45,1.42],
        [2.4,3.35,1.42],
        [1.45,3.35,1.42],
    ]
    
    let result = totalCombinations.reduce(0.0) {$0 + $1.reduce(1.0) {$0 * $1} }
    
    print(result) //->34.91405
    

    但我不确定它是否“优雅”。

    【讨论】:

    • 不确定在这种情况下是否更优雅,但您可以将* 运算符直接传递给reduce ($1.reduce(1, combine: *))
    • @Hamish,说得好。但它已经包含在 appzYourLife 的答案中。所以,我想我迟到了。
    【解决方案2】:

    也许这就是你要找的东西

    let a = [1.0, 2.0, 3.0]
    let b = [4.0, 5.0, 6.0]
    let c = [7.0, 8.0, 9.0, 10.0]
    
    let d = [a, b, c]
    
    let sum = d.reduce(0.0) { $0 + $1.reduce(1.0) {$0 * $1}}
    print(sum) // prints 5166.0
    

    【讨论】:

      【解决方案3】:

      给定这些值

      let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]
      

      让我们看看几种可能的方法

      解决方案 #1

      let sum =  lists.reduce(0) { $0 + $1.reduce(1, combine: *) }
      

      解决方案 #2

      如果你定义了这个扩展

      extension SequenceType where Generator.Element == Double {
          var product : Double { return reduce(1.0, combine: *) }
      }
      

      那你就可以写了

      let sum = lists.reduce(0) { $0 + $1.product }
      

      解决方案 #3

      有了上面定义的扩展,你也可以写

      let sum = lists.map { $0.product }.reduce(0, combine:+)
      

      解决方案 #4

      如果我们定义这两个后缀运算符

      postfix operator +>{}
      postfix func +>(values:[Double]) -> Double {
          return values.reduce(0, combine: +)
      }
      
      postfix operator *>{}
      postfix func *>(values:[Double]) -> Double {
          return values.reduce(1, combine: *)
      }
      

      我们可以写

      lists.map(*>)+>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2021-07-12
        • 2018-10-11
        • 1970-01-01
        相关资源
        最近更新 更多