;; sudoku brute force by jeffery (setq board0 '( ( 5 3 nil nil 7 nil nil nil nil) ( 6 nil nil 1 9 5 nil nil nil) (nil 9 8 nil nil nil nil 6 nil) ( 8 nil nil nil 6 nil nil nil 3 ) ( 4 nil nil 8 nil 3 nil nil 1 ) ( 7 nil nil nil 2 nil nil nil 6 ) (nil 6 nil nil nil nil 2 8 nil) (nil nil nil 4 1 9 nil nil 5 ) (nil nil nil nil 8 nil nil 7 9 ) )) ; rowcol - produce LL[row,col]. What is the built-in for this? (defun rowcol (LL row col) (nth col (nth row LL))) ; anyNIL -- returns whether any element of LL (i.e. a 'car') is nil (defun anyNIL (LL) (if (null LL) nil (if (not (consp LL)) nil (if (null (car LL)) t (or (anyNIL (car LL)) (anyNIL (cdr LL)))))) ) ; returns (row col) at which LL is nil (defun findNIL (LL) (dotimes (i (length LL)) (dotimes (j (length (car LL))) (if (null (rowcol LL i j)) (return-from findNIL (list i j))))) nil ) ; print out the board, inserting newlines between each row. (defun printboard (LL) (if (null LL) t (progn (print (car LL)) (printboard (cdr LL)))) ) ; check whether x can be placed at (row col) (defun check (LL row col x) ; check if x is on this row (dotimes (i (length LL)) (if (eq x (rowcol LL row i)) (progn (return-from check nil)))) ; check if x is on this column (dotimes (j (length (car LL))) (if (eq x (rowcol LL j col)) (progn (return-from check nil)))) ; check if x is in this 3x3 block of 9 cells (let ((metarow (truncate row 3)) (metacol (truncate col 3))) (dotimes (i 3) (dotimes (j 3) (progn (if (eq x (rowcol LL (+ (* metarow 3) i) (+ (* metacol 3) j))) (progn (return-from check nil) ) ) )))) ; if no conflicts, then it is OK t ) ;; place an x at col within a list (defun placeL (L col x) (if (= col 0) (cons x (cdr L)) (cons (car L) (placeL (cdr L) (- col 1) x) ))) ;; place an x at (row col) within a list of lists (defun place (LL row col x) (if (= row 0) (cons (placeL (car LL) col x) (cdr LL)) (cons (car LL) (place (cdr LL) (- row 1) col x)))) (defun sudo (LL) (if (not (anyNIL LL)) (progn (printboard LL) t) (let ((spot (findNIL LL))) (if (null spot) (progn (return-from sudo nil))) (dotimes (k 9) (if (check LL (car spot) (cadr spot) (+ k 1)) (let ((attempt (sudo (place LL (car spot) (cadr spot) (+ k 1))))) (if attempt (return-from sudo attempt)) ) ) ) nil ) ))