[英]Ruby compare 2 arrays of integer
Let's say i have 2 arrays with the same length filled with integers假设我有 2 个 arrays,长度相同,填充整数
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我想比较这些 arrays 并在新(c)数组中获得 output 所以它看起来像这样
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 A - 表示数字匹配:第二个数组中的一个数字与第一个数组中的一个数字相同,但在不同的 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: zip
以元素方式组合 arrays,然后按如下方式映射对:
'+'
if they are identical '+'
如果它们相同'-'
if the element from a
is included in b
'-'
如果来自a
的元素包含在b
中' '
otherwise ' '
否则Note that the result still reflects the element order ie the position of '+'
exactly tells you which elements are identical.请注意,结果仍然反映了元素顺序,即
'+'
的 position 准确地告诉您哪些元素是相同的。 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] ? '+' : '-') }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.