Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created June 20, 2018 17:15
Show Gist options
  • Save JoelQ/17a431958ba514fe0d0bd835e325e39e to your computer and use it in GitHub Desktop.
Save JoelQ/17a431958ba514fe0d0bd835e325e39e to your computer and use it in GitHub Desktop.
Edges to different groups

Problem

You have a graph where the nodes are in groups. You want to create edges between all nodes that are in different groups.

For example, given the following groups:

[[1, 2], [3], [4, 5]]

The graph should looke like:

Solution

def edges(all_groups)
  all_groups.combination(2).flat_map do |group, antigroup|
    group.product(antigroup)
  end
end

Demonstration

[1] pry(main)> groups = [[1, 2], [3], [4, 5]]
[2] pry(main)> groups.combination(2).flat_map { |g, ag| g.product(ag) }
# => [[1, 3], [2, 3], [1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment