Comparing Two Arrays Ignoring Element Order in Ruby

Comparing two arrays ignoring element order in Ruby

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

Check if two arrays have the same contents (in any order)

This doesn't require conversion to set:

a.sort == b.sort

Compare arrays in Ruby and print common elements

Hmmm... Not that I'm a judge, by why not use the Array#& method?

Set Intersection — Returns a new array containing elements common to the two arrays, excluding any duplicates. The order is preserved from the original array.

arr1 = [1, 2, 3, 4, 5]
arr2 = [1, 3, 5, 7, 9]
arr1 & arr2 # => [1, 3, 5]

How to get an array with true/false values after comparing 2 arrays in ruby?

This way?

a.zip(b).map { |a, b| a == b }

compare two arrays except element x,y,z (ruby)

There are probably plenty of more concise ways of doing this. Here's the first that came to my mind, which I'm sure could be improved upon.

def compare(array1, array2, ignore)
return false if array1.size != array2.size
0.upto(array1.size) do |i|
return false if !ignore.include?(i) && array1[i] != array2[i]
end
return true
end

Essentially, a manual array comparison. Check for same size, then check the elements one by one (but ignoring indices we are told to ignore). Break as soon as we know it's pointless to proceed.



Related Topics



Leave a reply



Submit