Vector 获取地图向量中最大关键点的向量
我有一个地图向量,看起来像这样:Vector 获取地图向量中最大关键点的向量,vector,map,clojure,key,Vector,Map,Clojure,Key,我有一个地图向量,看起来像这样: (def game-vec [{:game 1 :start 123456} {:game 2 :start 523456} {:game 3 :start 173456} {:game 1 :start 123456} {:game 1 :start 523456} {:game 2 :start 128456} {:game 3 :start 123256}])
(def game-vec [{:game 1 :start 123456}
{:game 2 :start 523456}
{:game 3 :start 173456}
{:game 1 :start 123456}
{:game 1 :start 523456}
{:game 2 :start 128456}
{:game 3 :start 123256}])
我想为每个
:game
取最大的:start
时间。最好的方法是什么?一种方法是从矢量获取所有游戏
可能是这样的:
(defn game-keys [from]
(set (map (fn [x] (:game x)) from)))
现在我们把所有独特的游戏都存储在某个地方,现在我们希望每个游戏都有最高的启动价值。如果我们筛选出正确的游戏,排序可能会有用
(defn games [key from]
(filter (fn [x] (= (:game x) key)) from))
所以我们可以得到我们想要的比赛,现在我们只需要最好的
(defn max-start [lst]
(first (sort (fn [x y] (> (:start x) (:start y))) lst)))
现在我们可以做:
(map (fn [x] (max-start (games x game-vec))) (game-keys game-vec))
然而,这只是一种方法,根据best的定义,可能还有更好的方法。使用@nickik中的max function思想迭代我的上一个解决方案。我确信这里的某个地方有一条直线:——) 我想到了这个:
(defn max-start-per-game [coll]
(into {} (map (fn [[k v]] [k (apply max (map :start v))])
(group-by :game game-vec))))
=> (max-start-per-game game-vec)
{1 523456, 2 523456, 3 173456}
我们的想法是在一个地方获得每场比赛的所有数据,然后取出数据用于首发。那就做一个最大值
更一般的版本:
(defn collect [coll sum-key collect]
(into {} (map (fn [[k v]] [k (map :start v)])
(group-by :game game-vec))))
(defn no-good-name
[coll f key1 key2]
(into {} (map (fn [[k v]] [k (f v)])
(collect coll key1 key2)))
(no-good-name game-vec #(apply max %) :game :start)
=> {1 523456, 2 523456, 3 173456}
(使用costum函数(在contrib的某个地方称为fmap)映射地图的所有值可能会更好,但你可以自己做)功能与Julian Chastang的代码非常相似,使用
reduce
我有:
(defn每场比赛的最大开始时间[游戏]
(减少(fn[res{:keys[game start]}]
(让[cur开始(获得res游戏0)
最大启动(最大启动电流启动)]
(assoc res游戏最大开始)
{}
游戏]
用户=>(每场游戏的最大开始vec)
{3 173456,2 523456,1 523456}
或者,使用
group by
amalloy的代码尽可能简洁。这里是另一个解决方案
user=> (map #(apply max-key :start %)
(vals (group-by :game game-vec)))
({:game 1, :start 523456}
{:game 2, :start 523456}
{:game 3, :start 173456})
(map(fn[x](:game x))from)是smae as(map:game form)我真的很喜欢这使得问题变得多么简单。它也是破坏性最小的,因为它保留了可能存在的任何其他钥匙!
(into {} (for [[game times] (group-by :game game-vec)]
{game (apply max (map :start times))}))
(defn max-start-per-game [games]
(reduce (fn [res {:keys [game start]}]
(let [cur-start (get res game 0)
max-start (max start cur-start)]
(assoc res game max-start)))
{}
games))
user=> (max-start-per-game game-vec)
{3 173456, 2 523456, 1 523456}
user=> (map #(apply max-key :start %)
(vals (group-by :game game-vec)))
({:game 1, :start 523456}
{:game 2, :start 523456}
{:game 3, :start 173456})