Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

is there any other simple,nicer way?

require 'pp'

a1 = ["02/28/10","Webinars","131","0","26 Feb 2010","0","3d, 8h, 49m, 18s"]
a2 = ["02/20/10","Webinars","131","9","26 Feb 2010","0","3d, 8h, 49m, 18s"]

def compare(array1,array2,ignore)

  tmp1 = Array.new
  tmp2 = Array.new
  0.upto(array1.length-1) {|index|
    if !ignore.include?(index)
      tmp1 << array1[index]
      tmp2 << array2[index]
    end
  }
  if tmp1 == tmp2 
    return true
  else
    return false    
  end
end

pp a1
pp a2
puts
puts compare(a1,a2,[0,3])

and the output is

["02/28/10", "Webinars", "131", "0", "26 Feb 2010", "0", "3d, 8h, 49m, 18s"]
["02/20/10", "Webinars", "131", "9", "26 Feb 2010", "0", "3d, 8h, 49m, 18s"]

true
like image 381
Radek Avatar asked Dec 10 '22 17:12

Radek


2 Answers

Simplest code (requires Ruby 1.8.7 or above):

def compare(array_a, array_b, ignore_list)
  array_a.zip(array_b).each_with_index.all? do |a, b, idx|
    a == b or ignore_list.include? idx
  end
end

I suspect it will be faster, too (since it uses a single zip rather than individually asking the array for each item) — though this probably isn't a case where speed matters greatly.

As an aside, almost any time I'm directly indexing an array (like some_array[i]) in Ruby rather than using a higher-order method such as map or each, I take that as a sign that I'm probably missing something in the standard library and the algorithm will probably be less efficient than the highly optimized library function.

like image 94
Chuck Avatar answered Dec 27 '22 12:12

Chuck


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.

like image 31
Matchu Avatar answered Dec 27 '22 11:12

Matchu