Last active
January 31, 2019 05:00
-
-
Save msg7086/893a85964cc5735ae9525f5763e6ff74 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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