比较两个数组,忽略Ruby中的元素顺序 [英] Comparing two arrays ignoring element order in Ruby

查看:110
本文介绍了比较两个数组,忽略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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆