rubyarrayscomparison

Comparing two arrays ignoring element order in Ruby


I need to check whether two arrays contain the same data in any order. Using the imaginary compare method, I would like to do:

arr1 = [1,2,3,5,4]
arr2 = [3,4,2,1,5]
arr3 = [3,4,2,1,5,5]

arr1.compare(arr2) #true    
arr1.compare(arr3) #false

I used arr1.sort == arr2.sort, which appears to work, but is there a better way of doing this?


Solution

  • Sorting the arrays prior to comparing them is O(n log n). Moreover, as Victor points out, you'll run into trouble if the array contains non-sortable objects. It's faster to compare histograms, O(n).

    In Ruby 2.7+, this can be done with tally:

    [1, 2, 1].tally == [2, 1, 1].tally
    #=> true
    

    For earlier Ruby versions: You'll find Enumerable#frequency in Facets, but implement it yourself, which is pretty straightforward, if you prefer to avoid adding more dependencies:

    require 'facets'
    [1, 2, 1].frequency == [2, 1, 1].frequency 
    #=> true