本文介绍了两个数组在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

我用 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)的。此外,维克多所指出的,即使你的数组​​包含非排序的对象遇到麻烦。它的速度更快,比较直方图,为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).

您会发现,但实现它自己,这是pretty简单,如果你preFER避免增加更多的依赖关系:

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中比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:16