Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two vectors in clojure no matter the order of the items

Tags:

clojure

I want to compare two vectors and find out if the items they have are the same no matter the order the items are in.

So..

right now in clojure:

(= [1 2 3] [3 2 1]) ;=> false

I want:

(other_fun [1 2 3] [3 2 1]) ;=> true

(other_fun [1 2 3 4] [3 2 1]) ;=> false

I could not find a containsAll like in java

like image 644
Federico Avatar asked Dec 05 '11 16:12

Federico


2 Answers

If you do care about duplicates, you can compare their frequency maps. These are maps with each collection element as a key and number of occurrences as a value. You create them using standard function frequencies, like in given examples.

Different order, same number of duplicates:

(= (frequencies [1 1 2 3 4])(frequencies [4 1 1 2 3]))

evaluates true.

Different order, different number of duplicates:

(= (frequencies [1 1 2 3 4])(frequencies [4 1 2 3]))

evaluates false.

So, you can write a function:

(defn other_fun [& colls]
  (apply = (map frequencies colls)))
like image 200
Goran Jovic Avatar answered Nov 18 '22 16:11

Goran Jovic


If you don't care about duplicates, you could create sets from both vectors and compare these:

(= (set [1 2 3]) (set [3 2 1])) ;=> true

As a function:

(defn set= [& vectors] (apply = (map set vectors)))
like image 19
Christian Berg Avatar answered Nov 18 '22 15:11

Christian Berg