(ns clojure.examples.collections
(:gen-class))
(defn alones
[ coll ]
(for [x coll :when (not (number? x)) ]
(str ":" x ))
)
(defn cartesian-pairs
"Function read col and return list of all possible pairs [ [x1 x2] .. [xi xj] ] alone elements [x] where xi not = xj and xi not number "
[ coll ]
(for [x coll y coll :when (not= x y) :when (and (not (number? x)) ( not (number? y)))
:when ( < (.indexOf coll x) (.indexOf coll y)) ]
(str ":" x "_" y ))
)
(def my-coll [123 45 "b" "f" "d" "e" 123 1234 4534] )
;(->> my-coll cartesian-pairs println )
(->
(reduce #(assoc %1 %2 (inc (%1 %2 0)))
{}
(reduce conj (cartesian-pairs my-coll) (alones my-coll) ))
println
)
The final Result :
{:e 1, :f_d 1, :d 1, :b_d 1, :b_f 1, :f 1, :d_e 1, :f_e 1, :b 1, :b_e 1}
Let's make small modification and reduce assoc formula will work with atomic collection
(def collection (atom {}))
(def my-coll [123 45 "b" "f" "d" "e" 123 1234 4534] )
;(->> my-coll cartesian-pairs println )
(->
(reduce #(swap! collection assoc %2 (inc (%1 %2 0)))
{}
(reduce conj (cartesian-pairs my-coll) (alones my-coll) ))
println
)
(println "Atomic collection: " @collection)
No comments:
Post a Comment