合并数组(如果它们包含一个或多个相同值) [英] Merge arrays if they contain one or more of the same value

查看:59
本文介绍了合并数组(如果它们包含一个或多个相同值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组数组:

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



<我想合并所有包含一个或多个相同值的数组。因此:

I would like to merge all arrays that contain one or more of the same value. So:

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

我正在为此寻找一种简洁的方法。有任何想法吗?

I'm struggling to find a concise approach for this. Any ideas?

推荐答案

我认为这是正确的:

def merge_em(a)
  return a if a.empty?
  rest = a.dup
  groups = []
  group = []
  while rest.any?
    group = rest.shift if group.empty?
    if i = rest.each_index.find { |i| (rest[i] & group).any? }
      group |= rest[i]
      rest.delete_at(i) 
      groups << group if rest.empty?
    else
      groups << group
      group = []
    end
  end
  groups
end

a = [[1, 2, 3], [3, 4, 5], [98, 99], [6, 7, 8], [8, 9], [9, 10]]
merge_em(a)
  #=> [[1, 2, 3, 4, 5], [98, 99], [6, 7, 8, 9, 10]] 

这篇关于合并数组(如果它们包含一个或多个相同值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆