1
\$\begingroup\$

It is a set of edges of a graph given. An edge is given as an array of its endpoints, e.g. [:a, :b]. The array can contain an arbitrary amount of endpoints. Therefore [] and [:b, :c, :d] are also valid edges.

I want to find all islands which means that I looking for unconnected sets of nodes. Here is my Ruby solution.

e = [[:a, :b],[:c, :d],[:b, :c, :e], [:f, :g]]
n = e.flatten.uniq
def islands(edges)
 edges.reduce([]) do |islands, edge|
 matches = islands.select { |island| island.any? { |node| edge.include?(node) } }
 if !matches.empty?
 island = matches.shift
 islands.delete_if { |i| matches.include?(i) }
 island.concat(matches.flatten)
 island.concat(edge)
 island.uniq!
 else
 islands << edge
 end
 islands
 end
end
puts islands(e).inspect
# => [[:a, :b, :c, :d, :e], [:f, :g]]

Is there room for improvement?

asked Aug 5, 2015 at 7:53
\$\endgroup\$
2
  • \$\begingroup\$ Found a similar question for C# \$\endgroup\$ Commented Aug 5, 2015 at 8:31
  • \$\begingroup\$ I am too lazy to write an answer, but with a quick-union algorithm it would be much, much faster. cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf \$\endgroup\$ Commented Aug 5, 2015 at 16:36

1 Answer 1

1
\$\begingroup\$
if !matches.empty? 

equals

if matches.any?

And the second is preferable, cause you don't have negation.

answered Aug 5, 2015 at 13:27
\$\endgroup\$
1
  • \$\begingroup\$ [nil].empty? == [nil].any? \$\endgroup\$ Commented Aug 6, 2015 at 20:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.