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

;;;; Cryptarithmetic Puzzles as N-ary CSPs

(defun make-two-two-four-csp ()
  "TWO + TWO = FOUR, with the carries C1, C2, C3 [Fig. 6.2]."
  (let ((digits (iota 10))
	(nonzero (iota 9 1))
	(bits (list 0 1)))
    (make-nary-csp
     :domains `((T ,@nonzero) (F ,@nonzero) (W ,@digits) (O ,@digits)
		(U ,@digits) (R ,@digits) (C1 ,@bits) (C2 ,@bits) (C3 ,@bits))
     :constraints
     (list (make-nary-constraint :scope '(T F W O U R)
				 :condition #'all-diff-constraint)
	   (make-nary-constraint
	    :scope '(O R C1)
	    :condition #'(lambda (o r c1) (= (+ o o) (+ r (* 10 c1)))))
	   (make-nary-constraint
	    :scope '(W U C1 C2)
	    :condition #'(lambda (w u c1 c2) (= (+ c1 w w) (+ u (* 10 c2)))))
	   (make-nary-constraint
	    :scope '(T O C2 C3)
	    :condition #'(lambda (tt o c2 c3) (= (+ c2 tt tt) (+ o (* 10 c3)))))
	   (make-nary-constraint :scope '(F C3) :condition #'=)))))

(defun two-two-four-solution? (solution)
  "Does the alist SOLUTION satisfy TWO + TWO = FOUR?"
  (flet ((v (var) (cdr (assoc var solution))))
    (let ((two (+ (* 100 (v 'T)) (* 10 (v 'W)) (v 'O)))
	  (four (+ (* 1000 (v 'F)) (* 100 (v 'O)) (* 10 (v 'U)) (v 'R))))
      (and (= (+ two two) four)
	   (= 6 (length (remove-duplicates
			 (mapcar #'v '(T W O F U R)))))))))
