I have a problem with 2 jugs. initial state is [0,0], capacity of each jug is [4,9], goal state is [0,6] legal moves: fill jug 1 or jug 2 till the end, empty jug 1 or jug 2 and poor one jug into the other one.
import search #get the interface
import sys
sys.setrecursionlimit(5000)
class two_jugs(search.Nodes):
#return the starting state vessel 1: 0, vessel 2: 0
def start(self):
return [0,0]
#returns true if node is equal to goal node
def goal(self,node):
return node ==(0,6)
#yields the successors of the configuration indicated by node
def succ(self,node):
# set capacities for vessel 1: 4, vessel 2 : 9
c = [4,9];
#stop at second last
for i in range(len(node)-1):
#create a safety copy
new_node = node[:]
#fill vessel 1
if new_node[i]<=0:
new_node[i]=c[i]
print new_node
#fill vessel 2
if new_node[i+1]<=0:
new_node[i+1]=c[i+1]
print new_node
#dump vessel i+1
if (new_node[i+1]>0):
new_node[i+1]=0
print new_node
#poor vessel i to vessel i+1
if (new_node[i+1]<c[i+1] and new_node[i]>0):
#calculate the difference
d = min(new_node[i],c[i+1]-new_node[i+1])
new_node[i]= new_node[i]-d
new_node[i+1]= new_node[i+1]+d
print new_node
#dump vessel i
if (new_node[i]>0):
new_node[i]=0
print new_node
#poor vessel i+1 to vessel 1
if (new_node[i]<c[i] and new_node[i+1]>0):
#calculate the difference
d = min(new_node[i+1],c[i]-new_node[i])
#set new node
new_node[i+1]= new_node[i+1]-d
new_node[i]= new_node[i]+d
yield new_node
print new_node
The question is since I have declared all the legal moves, why does my program return only the result of one legal move? Eg from starting state [0,0] when i run the program it returns [4,0],[0,4],[0,9] and other possible results untill the recursion stops but not my goal state. What am I missing?
breadth_first_search class:
def breadth_first_search(problem, candidates):
if not candidates: return
# make sure there is something in the candidate list
# I am modifying ’candidates’ list here.
# Why don’t I need to copy?
c = candidates.pop(0) # pop from front
node = c[-1] # must exist
if problem.goal(node): return c
# base case
succ = [s for s in problem.succ(node)]
for s in problem.succ(node):
candidates.append(c + [s])
# 1-step extension
return breadth_first_search(problem, candidates)
search class:
class Nodes:
def succ(self,n):
raise Exception, "Successor undefined"
def start (self):
raise Exception, "Start undefined"
def goal (self,n):
raise Exception, "Goal undefined"
the class that runs the program:
import decant
from breadth_first_search import *
dec = decant.Decant()
print breadth_first_search(dec,[[dec.start()]])