在Ruby中比较数组并删除重复项?

时间:2010-07-29 17:24:50

标签: ruby arrays compare duplicates

比较多个数组并删除重复数据的最简单方法是什么?

所以(在这种情况下,数组内的数组)......

a = [[2, 1], [3, 3], [7, 2], [5, 6]]  
b = [[2, 1], [6, 7], [9, 9], [4, 3]]  
c = [[2, 1], [1, 1], [2, 2], [9, 9]]  
d = [[2, 1], [9, 9], [2, 2], [3, 1]]  

......会出来(优先考虑数组a,然后是b,然后是c,然后是d)

a = [[2, 1], [3, 3], [7, 2], [5, 6]]  
b = [[6, 7], [9, 9], [4, 3]]  
c = [[1, 1], [2, 2]]  
d = [[3, 1]]  

2 个答案:

答案 0 :(得分:14)

它只是set difference或减法,你可以这样写。运算符重载可能是一种幸福:)

a就是这样。

a
[[2, 1], [3, 3], [7, 2], [5, 6]]

b = b - a
[[6, 7], [9, 9], [4, 3]]

c = c - b - a # or c - (a + b)
[[1, 1], [2, 2]]

d = d - c - b - a # or d - (a + b + c)
[[3, 1]]

答案 1 :(得分:1)

将所有数组放在一个大数组中:

a = [[[2, 1], [3, 3], [7, 2], [5, 6]],
[[2, 1], [6, 7], [9, 9], [4, 3]],
[[2, 1], [1, 1], [2, 2], [9, 9]],
[[2, 1], [9, 9], [2, 2], [3, 1]]]

你可以达到你想要的效果:

a.inject([]) do |acc, pairs|
  acc << pairs.uniq.reject{|pair| acc.flatten(1).member?(pair)}
end

注意:我不确定哪个Ruby版本Array#flatten开始接受参数。

编辑:这是Anurag的想法,适用于注入:

a.inject([]) do |acc, pairs|
  acc << (pairs - (acc.inject(&:+) || []))
end