简体   繁体   中英

Ruby compare 2 arrays of integer

Let's say i have 2 arrays with the same length filled with integers

a = [1,2,3,4]
b = [1,3,2,5]

And i want to compare these arrays and get an output in new (c) array so it would look like this

c = ["+","-","-"," "]

An empty space indicates that there is not a current digit in a first array

A - indicates a number match: one of the numbers in the second array is the same as one of the numbers in the first array but in a different position

Currently i have this comparison method and need to improve it

a.each_with_index.map {|x, i| b[i] == x ? '+' : '-'}

Something like this would work: (assuming unique elements)

a.zip(b).map do |i, j|
  if i == j
    '+'
  elsif b.include?(i)
    '-'
  else
    ' '
  end
end
#=> ["+", "-", "-", " "]

zip combines the arrays in an element-wise manner and then maps the pairs as follows:

  • '+' if they are identical
  • '-' if the element from a is included in b
  • ' ' otherwise

Note that the result still reflects the element order ie the position of '+' exactly tells you which elements are identical. You might want to sort / shuffle the result.

appearance = a.each_with_index.to_h b.map.with_index { |v, i| appearance[v].nil? ? " " : (v == a[i] ? '+' : '-') }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM