Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two lists consist of same elements

I have two functions which return lists of results of the same size and I'm trying to check if results are the same. Order in lists can be different. I'm currently using the following function:

lists_are_the_same(List1, List2) ->
    List1 -- List2 =:= [].

This function subtracts one list from the other and checks if the result is empty list. The problem is, such method is very slow and in my case lists can be fairly big.

Is there a faster way to check if two lists consist of exactly the same elements?

like image 489
Sergey Ovchinnik Avatar asked Sep 19 '16 10:09

Sergey Ovchinnik


2 Answers

A faster way is sorting each list and then compare them as follows:

lists_are_the_same(List1, List2) ->
    lists:sort(List1) =:= lists:sort(List2).

Based on the comment of Steve, it is important to know that all values in Erlang are sortable and have defined order, so it works for all possible list elements.

like image 105
Hamidreza Soleimani Avatar answered Oct 19 '22 22:10

Hamidreza Soleimani


In case all your elements are unique you might want to use ordsets instead of lists. You can see also the documentation about using A -- B operation:

The complexity of lists:subtract(A, B) is proportional to length(A)*length(B), meaning that it is very slow if both A and B are long lists. (If both lists are long, it is a much better choice to use ordered lists and ordsets:subtract/2.

Then you can check if they are equal via:

ordsets:is_subset(List1,List2) andalso ordsets:is_subset(List2,List1)
like image 45
A. Sarid Avatar answered Oct 19 '22 23:10

A. Sarid