;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: search/domains/pour.lisp

;;;; The Water Pouring Problem

;;; A state is a list of the water levels of the jugs, e.g. (0 0).  The
;;; actions are (fill i) and (dump i), which fill jug i to its capacity or
;;; empty it, and (pour i j), which pours jug i into jug j until i is empty
;;; or j is full.  The goal is to have one of the GOALS levels in some jug.

(defstructure (pour-problem (:include problem))
  "Pour water between jugs of the given CAPACITIES to measure out one of
  the GOALS levels, e.g. 4 units with jugs of 3 and 5."
  (capacities '(3 5))
  (goals '(4)))

(defmethod successors ((problem pour-problem) state)
  "Return the (action . state) pairs: fill or dump any jug, or pour one
  into another."
  (let ((capacities (pour-problem-capacities problem))
	(jugs (iota (length state)))
	(result nil))
    (dolist (i jugs)
      (unless (= (nth i state) (nth i capacities))
	(push (cons (list 'fill i) (pour-set state i (nth i capacities)))
	      result)))
    (dolist (i jugs)
      (unless (= (nth i state) 0)
	(push (cons (list 'dump i) (pour-set state i 0)) result)))
    (dolist (i jugs)
      (dolist (j jugs)
	(unless (= i j)
	  (let* ((a (nth i state))
		 (b (nth j state))
		 (amount (min a (- (nth j capacities) b))))
	    (push (cons (list 'pour i j)
			(pour-set (pour-set state i (- a amount))
				  j (+ b amount)))
		  result)))))
    (nreverse result)))

(defmethod goal-test ((problem pour-problem) state)
  "Is one of the goal levels in some jug?"
  (some #'(lambda (level) (member level (pour-problem-goals problem)))
	state))

(defun pour-set (state i level)
  "A copy of STATE with jug I at LEVEL."
  (let ((new (copy-list state)))
    (setf (nth i new) level)
    new))
