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

;;;; Sudoku as a Binary CSP

;;; The 81 cells are the variables 0 .. 80, numbered row by row.  A puzzle
;;; is a string of 81 characters, a digit for a given cell and any other
;;; character (e.g. a dot) for an empty one.  The neighbors of a cell are
;;; the other cells of its row, column and 3x3 box, which must all differ
;;; [Section 6.2.6].  The CSP is that of search/algorithms/csp-4e.lisp.

(defparameter *easy-sudoku*
  "..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3.."
  "A puzzle that arc consistency alone solves.")

(defparameter *harder-sudoku*
  "4173698.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......"
  "A puzzle that needs search after arc consistency.")

(defun sudoku-neighbors (cell)
  "The cells in the same row, column or box as CELL."
  (let ((row (floor cell 9))
	(col (mod cell 9)))
    (loop for other below 81
	  when (and (/= other cell)
		    (or (= (floor other 9) row)
			(= (mod other 9) col)
			(and (= (floor (floor other 9) 3) (floor row 3))
			     (= (floor (mod other 9) 3) (floor col 3)))))
	  collect other)))

(defun make-sudoku-csp (puzzle)
  "A CSP for the Sudoku PUZZLE, a string of 81 characters."
  (make-csp :variables (iota 81)
	    :domains (loop for cell below 81
			   for digit = (digit-char-p (char puzzle cell))
			   collect (cons cell (if (and digit (> digit 0))
						  (list digit)
						(iota 9 1))))
	    :neighbors (loop for cell below 81
			     collect (cons cell (sudoku-neighbors cell)))
	    :constraint-fn #'different-values-constraint))

(defun sudoku-solution-string (solution)
  "The digits of a SOLUTION alist ((cell . digit) ...), as a string."
  (map 'string #'(lambda (cell) (digit-char (cdr (assoc cell solution))))
       (iota 81)))
