我有两个序列h-keys
和h-values
。我需要建立一个所有可能映射的序列,将 h-keys
中的 n
元素与 h-values
中的元素关联起来。
(def h-keys [:a :b :c])
(def h-values [1 2])
(def res (f h-keys h-values 2))
(= (set res) #{{:a 1, :b 1} {:a 1 :b 2} {:a 2 :b 1} {:a 2 :b 2} {:a 1, :c 1} {:a 1 :c 2} {:a 2 :c 1} {:a 2 :c 2} {:c 1, :b 1} {:c 1 :b 2} {:c 2 :b 1} {:c 2 :b 2}})
我该如何编写f
?
最佳答案
使用组合学的替代实现
(require '[clojure.math.combinatorics :as combo])
(defn f
[keys vals n]
(->> (combo/cartesian-product (combo/combinations keys n)
(combo/selections vals n))
(map (partial apply zipmap))
set))
> (f [:a :b :c] [1 2] 2)
=> #{{:c 2, :a 1} {:c 1, :a 1} {:c 2, :a 2} {:b 1, :a 1} {:c 1, :a 2} {:b 2, :a 1} {:c 2, :b 1} {:c 1, :b 1} {:c 2, :b 2} {:b 1, :a 2} {:c 1, :b 2} {:b 2, :a 2}}
关于clojure - 从键和值列表中生成具有 n 个键的所有映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20883765/