我有一个数组数组:
a = [[1, 2, 3], [3, 4, 5], [6, 7, 8], [8, 9], [9, 10]]
我想合并包含一个或多个相同值的所有数组。所以:
a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
我正在努力为此找到一个简洁的方法。有什么想法吗?
答案 0 :(得分:3)
我认为这是正确的:
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]]
答案 1 :(得分:1)
这是怎么回事:
a = [[1, 2, 3], [3, 4, 5], [98, 99], [6, 7, 8], [8, 9], [9, 10]]
b = [ a.shift ] # start with first sequence
a.each do |seq|
match = nil
b.each do |existing_sequence|
match = existing_sequence if existing_sequence.any? {|x| seq.include? x }
end
if match
seq.each {|x| match << x } # coalese matching fragment
else
b << seq # new fragment
end
end
p b.map {|x| x.uniq }
# => [[1, 2, 3, 4, 5], [98, 99], [6, 7, 8, 9, 10]]