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

发布于 2024-09-12 00:45:35 字数 419 浏览 2 评论 0原文

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

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

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]]  

What would be the easiest way to compare multiple arrays, and remove duplicates?

So (arrays inside arrays in this case)...

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]]  

...would come out (with priority given to array a, then b, then c, then 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]]  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒废 2024-09-19 00:45:35

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

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]]

It's just set difference or subtraction and you can write it as such. Operator overloading can be a bliss :)

a is what it is.

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]]
两个我 2024-09-19 00:45:35

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

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

Having all the arrays in one big array:

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]]]

You can achieve what you want like this:

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

Note: I am not sure from which Ruby version Array#flatten started accepting arguments.

Edit: Here's Anurag's idea, applied to inject:

a.inject([]) do |acc, pairs|
  acc << (pairs - (acc.inject(&:+) || []))
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文