Created
February 16, 2015 05:44
-
-
Save JoshCheek/daf4d4d4aa7792aaa7bb to your computer and use it in GitHub Desktop.
shitty algorithm to solve the minimum cut
This file contains 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
def non_cyclical_paths adjacency, &block | |
adjacency.each do |current, associations| | |
_non_cyclical_paths adjacency, [current], &block | |
end | |
end | |
def _non_cyclical_paths adjacency, path, &block | |
current = path.last | |
adjacency[current].each do |adjacent| | |
next if path.include? adjacent | |
new_path = path + [adjacent] | |
block.call(new_path) | |
_non_cyclical_paths adjacency, new_path, &block | |
end | |
end | |
# a -- b | |
# | \ | | |
# c -- d -- e | |
edges = [ | |
[:a, :b], | |
[:a, :c], | |
[:a, :d], | |
[:b, :d], | |
[:c, :d], | |
[:d, :e], | |
] | |
adjacency = edges.each_with_object({}) { |(left, right), a| | |
a[left] ||= [] | |
a[right] ||= [] | |
a[left] << right | |
a[right] << left | |
} | |
nodes = edges.flatten.uniq | |
counts = nodes.map { |n| [n, Hash.new(0)] }.to_h | |
non_cyclical_paths adjacency do |path| | |
first, *, last = path | |
counts[first][last] += 1 | |
end | |
counts | |
# => {:a=>{:b=>3, :d=>3, :c=>3, :e=>3}, | |
# :b=>{:a=>3, :c=>4, :d=>3, :e=>3}, | |
# :c=>{:a=>3, :b=>4, :d=>3, :e=>3}, | |
# :d=>{:a=>3, :b=>3, :c=>3, :e=>1}, | |
# :e=>{:d=>1, :a=>3, :b=>3, :c=>3}} | |
counts.map { |node, node_counts| node_counts.values.min } # => [3, 3, 3, 1, 1] | |
.min # => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment