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

;;;; The Zebra Puzzle as a Binary CSP

;;; The variables are the 25 attributes (colors, pets, drinks, nationalities
;;; and smokes), and the value of each is the number (1 to 5) of the house
;;; that has it.  Attributes of the same kind are in different houses; the
;;; clues relate pairs of attributes.  The CSP is that of
;;; search/algorithms/csp-4e.lisp.

(defparameter *zebra-kinds*
  '((Red Yellow Blue Green Ivory)
    (Dog Fox Snails Horse Zebra)
    (OJ Tea Coffee Milk Water)
    (Englishman Spaniard Norwegian Ukrainian Japanese)
    (Kools Chesterfields Winston LuckyStrike Parliaments))
  "The attributes, grouped by kind.")

(defparameter *zebra-clues*
  '((Englishman Red same) (Spaniard Dog same) (Chesterfields Fox next-to)
    (Norwegian Blue next-to) (Kools Yellow same) (Winston Snails same)
    (LuckyStrike OJ same) (Ukrainian Tea same) (Japanese Parliaments same)
    (Kools Horse next-to) (Coffee Green same) (Green Ivory right-of))
  "The clues relating two attributes: (A B relation) says that the house
  of A is the same as, next to, or right of (one more than) that of B.
  The Norwegian lives in the first house and Milk is drunk in the middle
  one; these two clues are in the domains.")

(defun zebra-kind (attribute)
  (find-if #'(lambda (kind) (member attribute kind)) *zebra-kinds*))

(defun zebra-constraint (var1 house1 var2 house2)
  "Are VAR1 in HOUSE1 and VAR2 in HOUSE2 consistent with the clues?"
  (flet ((holds (relation x y)
	   (ecase relation
	     (same (= x y))
	     (next-to (= (abs (- x y)) 1))
	     (right-of (= x (+ y 1))))))
    (let ((clue (find-if #'(lambda (c)
			     (and (eq (first c) var1) (eq (second c) var2)))
			 *zebra-clues*))
	  (backward (find-if #'(lambda (c)
				 (and (eq (first c) var2) (eq (second c) var1)))
			     *zebra-clues*)))
      (cond (clue (holds (third clue) house1 house2))
	    (backward (holds (third backward) house2 house1))
	    ((eq (zebra-kind var1) (zebra-kind var2)) (/= house1 house2))
	    (t t)))))

(defun make-zebra-csp ()
  "The Zebra puzzle [Exercise 6.ZEBR]: who owns the zebra, and who drinks
  water?"
  (let* ((variables (apply #'append *zebra-kinds*))
	 (neighbors
	  (mapcar #'(lambda (A)
		      (cons A (remove-duplicates
			       (append
				(remove A (zebra-kind A))
				(loop for (x y nil) in *zebra-clues*
				      when (eq x A) collect y
				      when (eq y A) collect x)))))
		  variables)))
    (make-csp :variables variables
	      :domains (mapcar #'(lambda (A)
				   (cons A (case A
					     (Norwegian (list 1))
					     (Milk (list 3))
					     (t (iota 5 1)))))
			       variables)
	      :neighbors neighbors
	      :constraint-fn #'zebra-constraint)))
