簡體   English   中英

Ruby 比較 integer 的 2 arrays

[英]Ruby compare 2 arrays of integer

假設我有 2 個 arrays,長度相同,填充整數

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

我想比較這些 arrays 並在新(c)數組中獲得 output 所以它看起來像這樣

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

空格表示第一個數組中沒有當前數字

A - 表示數字匹配:第二個數組中的一個數字與第一個數組中的一個數字相同,但在不同的 position

目前我有這種比較方法,需要改進它

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

像這樣的東西會起作用:(假設獨特的元素)

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

zip以元素方式組合 arrays,然后按如下方式映射對:

  • '+'如果它們相同
  • '-'如果來自a的元素包含在b
  • ' '否則

請注意,結果仍然反映了元素順序,即'+'的 position 准確地告訴您哪些元素是相同的。 您可能想要對結果進行排序/打亂。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM