tags:

views:

76

answers:

2

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?

+6  A: 

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

pelotom
I want to cater for duplicate elements as well.So List(1,2,3,3) should not equal (List(3,2,1))
ssanj
Ok, edited to reflect that :)
pelotom
List(1,2,3,3).sorted != List(3,2,1)
ssanj
I'm confused about what you want. You want to make sure that the exact same set of elements occurs the exact same number of times in each list, irrespective of order, right?
pelotom
Sorry, I meant:List(1,2,3,3).sorted != List(3,2,1).sortedYes, just the same number of elements and the same elements - could be in a different order.
ssanj
then my solution works...
pelotom
it sounds like you're saying you want the list to be the same size, but you don't care if the first list has 10 '3's and the second list has 4 '3's, just that they both have at least one '3' and the resulting list sizes are equal.... is that it?
pelotom
btw, if you want `List(1,2,3,3)` to be considered equal to `List(3,2,1)` according to this hypothetical function, then comparing list sizes would rule that out...
pelotom
List(1,2,3,3) does not equal List(3,2,1) in my prob. List(1,2,3,3) does equal List(3,1,2,3) tho. So they have to have:1. The same number of elements (hence size does matter)2. The same elements irrespective of order.
ssanj
pelotom
I think my question may be confusing.I do care about the number of instances being the same, which means the length of each should be the same.Basically:List(1,2,3) should equal (List(3,2,1)),List(1,2,3,3) should equal (List(3,2,1,3),List(1,2,3,4) should not equal (List(3,2,1,3)),List(1,2,3,3,3) should not equal (List(3,2,1,3,4)),List(1,2,3,3,3) should not equal (List(3,2,1,3))
ssanj
then you want `l1.sorted == l2.sorted`
pelotom
That's the one! :) thanks mate! :)
ssanj
+4  A: 

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.

Dave Griffith