@@ -883,6 +883,46 @@ def and_search(states, problem, path):
883883directions8 .update ({'NW' : (- 1 , 1 ), 'NE' : (1 , 1 ), 'SE' : (1 , - 1 ), 'SW' : (- 1 , - 1 )})
884884
885885
886+ class PourProblem (Problem ):
887+ """Problem about pouring water between jugs to achieve some water level.
888+ Each state is a tuple of levels. In the initialization, provide a tuple of
889+ capacities, e.g. PourProblem(initial=(2, 4, 3), goals={7}, capacities=(8, 16, 32)),
890+ which means three jugs of capacity 8, 16, 32 currently filled with 2, 4, 3 units
891+ of water, respectively, and the goal is to get a level of 7 in any one of the jugs."""
892+
893+ def __init__ (self , initial = None , goals = (), capacities = None ):
894+ super ().__init__ (initial , goals )
895+ self .goals = goals
896+ self .capacities = capacities
897+
898+ def actions (self , state ):
899+ """The actions executable in this state: fill or dump any jug, or pour one into another."""
900+ jugs = range (len (state ))
901+ return ([('Fill' , i ) for i in jugs if state [i ] != self .capacities [i ]] +
902+ [('Dump' , i ) for i in jugs if state [i ] != 0 ] +
903+ [('Pour' , i , j ) for i in jugs for j in jugs if i != j ])
904+
905+ def result (self , state , action ):
906+ """The state that results from executing this action in this state."""
907+ result = list (state )
908+ act , i , j = action [0 ], action [1 ], action [- 1 ]
909+ if act == 'Fill' : # fill jug i to its capacity
910+ result [i ] = self .capacities [i ]
911+ elif act == 'Dump' : # empty jug i
912+ result [i ] = 0
913+ elif act == 'Pour' : # pour jug i into jug j
914+ a , b = state [i ], state [j ]
915+ result [i ], result [j ] = ((0 , a + b ) if (a + b <= self .capacities [j ])
916+ else (a + b - self .capacities [j ], self .capacities [j ]))
917+ else :
918+ raise ValueError ('unknown action' , action )
919+ return tuple (result )
920+
921+ def goal_test (self , state ):
922+ """True if any of the jugs has a level equal to one of the goal levels."""
923+ return any (level in self .goals for level in state )
924+
925+
886926class PeakFindingProblem (Problem ):
887927 """Problem of finding the highest peak in a limited grid"""
888928
0 commit comments