Ruby 中比较两个数组忽略元素顺序
我需要检查两个数组是否以任何顺序包含相同的数据。 使用想象的比较方法,我想做:
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是一个适用于不可排序数组的版本
Here is a version that will work on unsortable arrays
如果数组长度相同,则使用差分法
https://ruby-doc.org/core- 2.7.0/Array.html#method-i-difference
否则你可以使用
Use difference method if length of arrays are the same
https://ruby-doc.org/core-2.7.0/Array.html#method-i-difference
Otherwise you could use
最简单的方法是使用交集:
因此该语句
将为
true
。如果您想检查array1
是否包含array2
或相反(即不同),这是最好的解决方案。您也不会摆弄数组或更改项目的顺序。如果您希望两个数组的大小相同,您还可以比较它们的长度:
这也是最快的方法(如果我错了,请纠正我)
The easiest way is to use intersections:
So the statement
Will be
true
. This is the best solution if you want to check whetherarray1
containsarray2
or the opposite (that is different). You're also not fiddling with your arrays or changing the order of the items.You can also compare the length of both arrays if you want them to be identical in size:
It's also the fastest way to do it (correct me if I'm wrong)
在比较之前对数组进行排序的时间复杂度为 O(n log n)。此外,正如 Victor 指出的那样,如果数组包含不可排序的对象,您将会遇到麻烦。比较直方图更快,O(n)。
您会在 Facets 中找到 Enumerable#Frequency,但要实现它如果您希望避免添加更多依赖项,那么这非常简单:
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:
如果您知道任何数组中都没有重复(即所有元素都是唯一的或者您不关心),那么使用集合是直接且可读的:
If you know that there are no repetitions in any of the arrays (i.e., all the elements are unique or you don't care), using sets is straight forward and readable:
实际上,您可以通过猴子修补 Array 类来实现此
#compare
方法像这样:请记住,猴子修补很少被认为是一种好的做法,使用它时应该小心谨慎。
可能有更好的方法来做到这一点,但这就是我想到的。希望有帮助!
You can actually implement this
#compare
method by monkey patching the Array class like this:Keep in mind that monkey patching is rarely considered a good practice and you should be cautious when using it.
There's probably is a better way to do this, but that's what came to mind. Hope it helps!
我发现的最优雅的方式:
The most elegant way I have found:
您可以打开
array
类并定义这样的方法。或者简单地使用
You can open
array
class and define a method like this.OR use simply