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

;;;; Kakuro Puzzles as N-ary CSPs

;;; A puzzle is a list of rows.  Each element is * (a blocked cell), _ (a
;;; cell to fill with a digit from 1 to 9), or a clue (down right): DOWN is
;;; the sum of the run of cells below, RIGHT the sum of the run of cells on
;;; its right, and nil means no run.  The digits of a run are all
;;; different.

(defparameter *kakuro1*
  '((*      *      *     (6 nil) (3 nil))
    (*      (4 nil) (3 3) _       _)
    ((nil 10) _     _     _       _)
    ((nil 3)  _     _     *       *))
  "A Kakuro puzzle of difficulty 0.")

(defparameter *kakuro2*
  '((*        (10 nil) (13 nil) *)
    ((nil 3)  _        _        (13 nil))
    ((nil 12) _        _        _)
    ((nil 21) _        _        _))
  "A Kakuro puzzle of difficulty 0.")

(defun kakuro-cell (row col)
  "The name of the variable of a cell."
  (format nil "X~2,'0D~2,'0D" row col))

(defun make-kakuro-csp (puzzle)
  "A CSP for a Kakuro PUZZLE: a variable (a digit) for each cell, and for
  each clue a sum constraint and an all-different constraint on its run."
  (let ((domains nil)
	(constraints nil)
	(rows (length puzzle)))
    (flet ((elt-at (row col) (nth col (nth row puzzle)))
	   (add-run (scope sum)
	     (push (make-nary-constraint :scope scope
					 :condition (sum-constraint sum))
		   constraints)
	     (push (make-nary-constraint :scope scope
					 :condition #'all-diff-constraint)
		   constraints)))
      (dotimes (row rows)
	(dotimes (col (length (nth row puzzle)))
	  (let ((element (elt-at row col)))
	    (cond ((eq element '_)
		   (push (cons (kakuro-cell row col) (list 1 2 3 4 5 6 7 8 9))
			 domains))
		  ((consp element)
		   (when (first element)        ; down
		     (add-run (loop for k from (+ row 1) below rows
				    while (eq (elt-at k col) '_)
				    collect (kakuro-cell k col))
			      (first element)))
		   (when (second element)       ; right
		     (add-run (loop for k from (+ col 1)
				    below (length (nth row puzzle))
				    while (eq (elt-at row k) '_)
				    collect (kakuro-cell row k))
			      (second element))))))))
      (make-nary-csp :domains (nreverse domains)
		     :constraints (nreverse constraints)))))

(defun display-kakuro (puzzle assignment &optional (stream t))
  "Print the puzzle with the digits of ASSIGNMENT, an alist."
  (dotimes (row (length puzzle))
    (dotimes (col (length (nth row puzzle)))
      (let ((element (nth col (nth row puzzle))))
	(cond ((eq element '*) (format stream "[*]~6T"))
	      ((eq element '_)
	       (let ((binding (assoc (kakuro-cell row col) assignment
				     :test #'equal)))
		 (format stream "[~A]~6T" (if binding (cdr binding) "_"))))
	      (t (format stream "~A\\~A~6T"
			 (or (first element) "") (or (second element) ""))))))
    (format stream "~%")))
