bitbckt (owner)

Revisions

gist: 200280 Download_button fork
public
Public Clone URL: git://gist.github.com/200280.git
Embed All Files: show embed
sudoku.clj #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(ns sudoku
  (:use [clojure.contrib.combinatorics :only (selections)]))
 
(defn numerical [s]
  (if (= "." (str s))
    0
    (Integer/parseInt (str s))))
 
(defn read-matrix [file]
  (vec (map #(vec %)
            (partition 9
                       (map numerical
                            (remove #(= \newline %)
                                    (slurp file)))))))
 
(defn check-row [matrix row value]
  (not-any? #(= value %)
            (nth matrix row)))
 
(defn check-column [matrix col value]
  (not-any? #(= value %)
            (map #(nth % col) matrix)))
 
(defn check-block [matrix row col value]
  (let [i (* 3 (/ row 3))
        j (* 3 (/ col 3))]
    (not-any? #(= value %)
              (map #(subvec % j (+ j 3))
                    (subvec matrix i (+ i 3))))))
 
(defn possible? [matrix row col value]
  (and
   (check-row matrix row value)
   (check-column matrix col value)
   (check-block matrix row col value)))
 
(defn solve-square [matrix row col]
  (for [x (range 1 10) :when (possible? matrix row col x)] x))