Clojure: how to merge several sorted vectors of vectors into common structure? -
need help. stuck on intuitively simple task.
i have few vectors of vectors. first element of each of sub-vectors numeric key. parent vectors sorted these keys. example:
[[1 b] [3 c d] [4 f d] .... ] [[1 aa bb] [2 cc dd] [3 ww qq] [5 f]... ] [[3 ccc ddd] [4 fff ddd] ...]
need clarify key values in nested vectors may missing, sorting order guaranteed.
i need merge of these vectors unified structure numeric keys. need now, key missed in original vector or vectors.
like this:
[ [[1 b][1 aa bb][]] [[][2 cc dd]] [[3 c d][3 ww qq][3 ccc ddd]] [[4 f d][][4 fff dd]]...]
you can break problem down 2 parts:
1) unique keys in sorted order
2) each unique key, iterate through list of vectors, , output either entry key, or empty list if missing
to unique keys, pull out keys lists, concat them 1 big list, , put them sorted-set:
(into (sorted-set) (apply concat (for [vector vectors] (map first vector))))
if start list of vectors of:
(def vectors [[[1 'a 'b] [3 'c 'd] [4 'f 'd]] [[1 'aa 'bb] [2 'cc 'dd] [3 'ww 'qq] [5 'f]] [[3 'ccc 'ddd] [4 'fff 'ddd]]])
then sorted set of:
=> #{1 2 3 4 5}
so far good. each key in sorted set need iterate through vectors, , entry key, or empty list if it's missing. can using 2 'for' forms , 'some' find entry (if present)
(for [k #{1 2 3 4 5}] (for [vector vectors] (or (some #(when (= (first %) k) %) vector ) [])))
this yields:
=> (([1 b] [1 aa bb] []) ([] [2 cc dd] []) ([3 c d] [3 ww qq] [3 ccc ddd]) ([4 f d] [] [4 fff ddd]) ([] [5 f] []))
which think want. (if need vectors , not lists, use "(into [] ...)" in appropriate places.)
putting together, get:
(defn unify-vectors [vectors] (for [k (into (sorted-set) (apply concat (for [vector vectors] (map first vector))))] (for [vector vectors] (or (some #(when (= (first %) k) %) vector) [])))) (unify-vectors [[[1 'a 'b] [3 'c 'd] [4 'f 'd]] [[1 'aa 'bb] [2 'cc 'dd] [3 'ww 'qq] [5 'f]] [[3 'ccc 'ddd] [4 'fff 'ddd]]]) => (([1 b] [1 aa bb] []) ([] [2 cc dd] []) ([3 c d] [3 ww qq] [3 ccc ddd]) ([4 f d] [] [4 fff ddd]) ([] [5 f] []))
Comments
Post a Comment