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
Prevent Rails Test from Deleting Seed Data
Installing Jekyll on Ubuntu 14.04
How to Reverse a 'Rails Generate'
How to Run a Single Rspec Test
Change the Binding of a Proc in Ruby
How to Debug in Rubymine 4.5 Using Ruby 1.9.3
Using Ruby Convert Numbers to Words
Project Euler 1:Find the Sum of All the Multiples of 3 or 5 Below 1000
Errno::Econnrefused: Connection Refused - Connect(2) for Action Mailer
Is There a Built-In Binary-Search in Ruby
Typing 'Rails Console' Doesn't Start
Ruby SQLite3 Installation SQLite3_Libversion_Number() MACos Sierra
Peer-To-Peer File Sharing with Web Sockets
Os X Mountain Lion: Gcc-4.2 No Such File or Directory
Portable Ruby on Rails Environment