Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an API method that compares contents of a Seq irrespective of order?

Tags:

equality

scala

Assuming:

val l1 = List(1,2,3)  val l2 = List(2,3,1) 

I want a method that confirms that l1 is equal to l2 (as in same contents but different order). Is there an API method on List/Seq to do this?

l1.sameElements(l2) 

does not work as it verifies order as well.

I've come up with the following:

l1.foldLeft(l1.size == l2.size)(_ && l2.contains(_)) 

Is there anything more succinct than the above to do this comparison?

like image 401
ssanj Avatar asked Sep 01 '10 23:09

ssanj


People also ask

How do you know if a list has the same element?

Using sets Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.

How do you check if lists have the same elements Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.


2 Answers

If what you want is "these lists contain the same elements, irrespective of order or repetitions":

l1.toSet == l2.toSet

If what you want is "these lists contain the same elements, and with the same number of repetitions of each":

l1.sorted == l2.sorted

If what you want is "these lists contain the same elements and are the same size, but the number of repetitions of a given element can differ between the two lists":

l1.size == l2.size && l1.toSet == l2.toSet

like image 112
Tom Crockett Avatar answered Sep 19 '22 17:09

Tom Crockett


While

l1.sorted == l2.sorted 

is correct, it's runtime performance is O(n log n), because of the sorting. For large lists, you are probably better with

l1.groupBy(identity) == l2.groupBy(identity) 

which should be O(n), assuming a decent implementation of groupBy.

like image 36
Dave Griffith Avatar answered Sep 20 '22 17:09

Dave Griffith