Skip to content

Instantly share code, notes, and snippets.

@thsig
Last active April 11, 2016 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thsig/e54dc1c7713e236d47b4cadc160f825d to your computer and use it in GitHub Desktop.
Save thsig/e54dc1c7713e236d47b4cadc160f825d to your computer and use it in GitHub Desktop.
brute-force count of the number of Hamiltonian paths on the surface of a cube from a given starting vertex
require 'set'
class Hash
def dig(key, *rest)
if value = (self[key] rescue nil)
if rest.empty?
value
elsif value.respond_to?(:dig)
value.dig(*rest)
end
end
end
end
# adjacency matrix
adj = {
1 => Set.new([2,3,4]),
2 => Set.new([1,5,7]),
3 => Set.new([1,5,6]),
4 => Set.new([1,6,7]),
5 => Set.new([2,3,8]),
6 => Set.new([3,4,8]),
7 => Set.new([2,4,8]),
8 => Set.new([5,6,7])
}
n_paths = 0
# all hops except for the last one
hops = (0..5)
# brute force, try all 7! possibilities and count the Hamiltonian paths among them
[2,3,4,5,6,7,8].permutation do |path|
if adj[path[0]].include?(1) && hops.find{|n| !adj[path[n]].include?(path[n+1])}.nil?
puts path.to_s
n_paths += 1
end
end
puts "number of paths: #{n_paths}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment