fork download
  1. require 'set'
  2. f = -> a {
  3. h = a.map {|s| s.split('=')}.flatten.uniq.map.with_index.to_h
  4. a.each_with_object([]) {|s, acc|
  5. x, xs, y, ys = s.split('=').map {|k| [h[k], acc.find {|b| b.include? h[k]}]}.flatten(1)
  6. if xs && ys then xs.merge(acc.delete ys)
  7. elsif xs then xs << y
  8. elsif ys then ys << x
  9. else acc << SortedSet[x, y]
  10. end
  11. }.sort_by(&:first).map {|a| a.map &h.invert.method(:[]) }
  12. }
  13. a = ["a1=a2", "b1=b2", "b3=b2", "c1=c2", "e1=e2",
  14. "a3=a4", "c3=c4", "e1=e3", "a2=a4", "c3=c1",
  15. "b3=a4", "c2=d1", "a4=a5", "d2=c1", "b4=b3", "d3=c3"]
  16. p f.(a)
  17.  
Success #stdin #stdout 0.01s 8376KB
stdin
Standard input is empty
stdout
[["a1", "a2", "b1", "b2", "b3", "a3", "a4", "a5", "b4"], ["c1", "c2", "c3", "c4", "d1", "d2", "d3"], ["e1", "e2", "e3"]]