Skip to content

Instantly share code, notes, and snippets.

@flash-gordon
Created September 5, 2019 21:04
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 flash-gordon/a72c2884df696178917137705d501207 to your computer and use it in GitHub Desktop.
Save flash-gordon/a72c2884df696178917137705d501207 to your computer and use it in GitHub Desktop.
require 'continuation'
@cc = []
def backtrack(*choices)
if @cc.empty?
raise
else
@cc.pop.call
end
end
def amb(*choices)
backtrack if choices.empty?
choices.each do |choice|
callcc do |cc|
@cc << cc
return choice
end
end
backtrack
end
# s = amb(1, 2, 3, 4, 5, 6, 7, 8, 9)
# m = amb(1, 2, 3, 4, 5, 6, 7, 8, 9)
# e = amb(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
# n = amb(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
# d = amb(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
# o = amb(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
# r = amb(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
# y = amb(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
choices = [*1..9, 0]
s = amb(*(choices - [0]))
m = amb(*(choices - [0, s]))
e = amb(*(choices - [s, m]))
n = amb(*(choices - [s, m, e]))
d = amb(*(choices - [s, m, e, n]))
o = amb(*(choices - [s, m, e, n, d]))
r = amb(*(choices - [s, m, e, n, d, o]))
y = amb(*(choices - [s, m, e, n, d, o, r]))
constraint = [s, e, n, d, m, o, r, y].uniq.size == 8 && \
"#{s}#{e}#{n}#{d}".to_i + "#{m}#{o}#{r}#{e}".to_i == "#{m}#{o}#{n}#{e}#{y}".to_i
amb unless constraint
puts "#{s}#{e}#{n}#{d} + #{m}#{o}#{r}#{e} == #{m}#{o}#{n}#{e}#{y}"
@flash-gordon
Copy link
Author

$ time ruby backtracking.rb 
9567 + 1085 == 10652
ruby backtracking.rb  8.00s user 0.05s system 99% cpu 8.089 total

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment