Hello Everyone,
I am trying to come to terms with continuations and I am failing
miserably.
I have a method “traverse” which basically is a traversal algorithm
for a sudoko game.
To learn more about continuations I tried to write one that used
continuations instead: traverse_cc.
This does not work at all. I have tried many different usages but the
main problem seems to be that the local variable state is not
restored when the continuation is called. I thought that it was
supposed to do that.
Any help will be appreciated
Regards
Anders
def traverse(debug)
@solve_count += 1
print “F” if debug
return true if @available_positions.empty?
position = @available_positions.pop
position.reset
position.possible_numbers.each do |num|
position.place(num)
return true if traverse(debug)
end
position.place(nil)
@available_positions.push position
print “B” if debug
return false
end
def traverse_cc(debug)
$c_stack = []
available_positions = @available_positions.dup
position = nil
possible_numbers = nil
until (available_positions.empty?)
@solve_count += 1
callcc do |cont|
$c_stack.push cont
print “F” if debug
position = available_positions.pop
position.reset
end
possible_numbers = position.possible_numbers
if possible_numbers.empty?
print "pop #{available_positions.size}:#
{possible_numbers.size}:#{$c_stack.size}\n"
$c_stack.pop.call
else
num = possible_numbers.pop
position.place(num)
end
print "#{available_positions.size}:#{possible_numbers.size}:#
{$c_stack.size}, "
end
return true
end