Comparing two arrays ignoring element order in Ruby

后端 未结 8 564
春和景丽
春和景丽 2020-12-08 02:14

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         


        
8条回答
  •  心在旅途
    2020-12-08 02:36

    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).

    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
    

提交回复
热议问题