比较两个数组而忽略 Ruby 中的元素顺序 [英] Comparing two arrays ignoring element order in Ruby
问题描述
我需要检查两个数组是否以任何顺序包含相同的数据.使用虚构的 compare
方法,我想做:
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
我使用了 arr1.sort == arr2.sort
,这似乎有效,但有没有更好的方法呢?
I used arr1.sort == arr2.sort
, which appears to work, but is there a better way of doing this?
推荐答案
在比较数组之前对数组进行排序是 O(n log n).此外,正如 Victor 指出的那样,如果数组包含不可排序的对象,您会遇到麻烦.比较直方图更快,O(n).
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).
您会在 Facets 中找到 Enumerable#frequency,但是自己实现它,这非常简单,如果您不想添加更多依赖项:
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
这篇关于比较两个数组而忽略 Ruby 中的元素顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!