Skip to content

Instantly share code, notes, and snippets.

@msg7086
Last active January 31, 2019 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msg7086/893a85964cc5735ae9525f5763e6ff74 to your computer and use it in GitHub Desktop.
Save msg7086/893a85964cc5735ae9525f5763e6ff74 to your computer and use it in GitHub Desktop.
input = [
[1,2,3],
[2,3],
[3,5],
[10,15]
]
# 二级引用
class Ref
attr_accessor :obj
def initialize(obj)
@obj = obj
end
end
def group(input)
dict = {}
input.each do |row|
# 定义一个指向集合的二级引用
ref = Ref.new(row)
overlapping = [ref]
row.each do |value|
if dict[value]
overlapping << dict[value]
else
dict[value] = ref
end
end
next if overlapping == 1
# 多个集合需要合并
new_set = overlapping.uniq.map(&:obj).reduce(&:+).uniq
overlapping.each {|ref| ref.obj = new_set}
end
# 对象去重输出
dict.values.map(&:obj).uniq
end
p group(input)
#=> [[3, 5, 2, 1], [10, 15]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment