【问题标题】:Sum of values in 2D vector二维向量中的值之和
【发布时间】:2020-01-10 12:05:39
【问题描述】:

我有一个看起来像这样的二维向量

[[1917 2850]
 [1623 34]
 [1917 300]]

我想获取第一个值相同的所有值的第二个值的总和。所以会产生这样的结果

 [[1917 3150]
 [1623 34]]

如何在 Clojure 中做到这一点?我想也许我可以添加到排序集中,但我不确定这是最好的。

【问题讨论】:

  • (vec (reduce (fn [acc [l r]] (update acc l (fnil + 0) r)) {} data)) ,但实际上,您应该先阅读一些关于 clojure 的介绍...

标签: arrays clojure


【解决方案1】:

一步一步做:

使用sort-by + partition-by...

(->> [[1917 2850]
      [1623 34]
      [1917 300]]
     ;; sort by first element
     (sort-by first)
     ;; split when first element changes
     (partition-by (comp identity first))
     ;; for each partition, take first element of first row
     ;; as key, and sum up second element of each row as value
     (mapv (fn [xs]
             [(ffirst xs)
              (apply + (map second xs))])))
;; => [[1623 34]
;;     [1917 3150]]

...或使用group-by

(->> [[1917 2850]
      [1623 34]
      [1917 300]]
     ;; group by first element
     (group-by first)
     ;; for each group, take the group key
     ;; and sum up second element of each row in the group
     (mapv (fn [[g xs]]
             [g (apply + (map second xs))])))

【讨论】:

    【解决方案2】:

    在这些书籍和网站上阅读一下:

    the Clojure CheatSheet。我会从group-by开始:

    (ns tst.demo.core
      (:use tupelo.core tupelo.test))
    
    (def data
      [[1917 2850]
       [1623 34]
       [1917 300]] )
    
    (group-by first data) => 
        {1917 [[1917 2850] 
               [1917 300]], 
         1623 [[1623 34]]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2022-11-20
      • 2011-06-03
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多