;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: logic/domains/map-coloring-sat.lisp

;;;; Map Coloring as a Propositional Satisfiability Problem

;;; The symbol R_C (e.g. WA_R) says that region R has color C.  Each region
;;; has at least one color and at most one, and neighboring regions do not
;;; have the same color.  A model of the sentence, as returned by
;;; DPLL-SATISFIABLE, is a coloring of the map.

(defun map-coloring-symbol (region color)
  "The propositional symbol saying that REGION has COLOR."
  (intern (format nil "~A_~A" region color)))

(defun make-map-coloring-sat (colors neighbors)
  "A sentence in CNF that is satisfiable iff the map can be colored with
  COLORS.  NEIGHBORS is an alist ((region . adjacent-regions) ...) or a
  string in the format of PARSE-NEIGHBORS (see search/domains/map-coloring.lisp)."
  (when (stringp neighbors)
    (setf neighbors (parse-neighbors neighbors)))
  (let ((clauses nil)
	(done nil))			; regions whose neighbor clauses are in
    (dolist (entry neighbors)
      (let ((region (car entry)))
	(push region done)
	;; at least one color
	(push (disjunction (mapcar #'(lambda (c) (map-coloring-symbol region c))
				   colors))
	      clauses)
	;; at most one color
	(loop for (c1 . others) on colors do
	      (dolist (c2 others)
		(push `(or (not ,(map-coloring-symbol region c1))
			   (not ,(map-coloring-symbol region c2)))
		      clauses)))
	;; neighbors differ, once for each pair of neighbors
	(dolist (other (cdr entry))
	  (unless (member other done)
	    (dolist (c colors)
	      (push `(or (not ,(map-coloring-symbol region c))
			 (not ,(map-coloring-symbol other c)))
		    clauses))))))
    (conjunction (nreverse clauses))))

(defun map-coloring-sat-solution (model colors neighbors)
  "The coloring ((region . color) ...) of a MODEL of MAKE-MAP-COLORING-SAT."
  (when (stringp neighbors)
    (setf neighbors (parse-neighbors neighbors)))
  (mapcar #'(lambda (entry)
	      (cons (car entry)
		    (find-if #'(lambda (c)
				 (eq (cdr (assoc (map-coloring-symbol (car entry) c)
						 model))
				     t))
			     colors)))
	  neighbors))
