我有两个seq h-keys
和h-values
。我需要构建一系列所有可能的地图,这些地图将来自n
的{{1}}元素与来自h-keys
的元素相关联。
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}})
?
答案 0 :(得分:1)
使用组合学的替代实施
(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}}
答案 1 :(得分:1)
(require '[clojure.math.combinatorics :as combo])
(defn f [keys values n]
(set (for [res-keys (combo/combinations keys n)
res-values (combo/selections values n)]
(zipmap res-keys res-values))))
答案 2 :(得分:0)
(require '[clojure.math.combinatorics :as combo])
(defn f [keys values n]
(mapcat (fn [keys]
(map (fn [values]
(apply assoc {} (interleave keys values)))
(combo/selections values n)))
(combo/combinations keys n)))