Skip to content

Instantly share code, notes, and snippets.

@bitbckt
Created October 3, 2009 00:35
Show Gist options
  • Save bitbckt/200280 to your computer and use it in GitHub Desktop.
Save bitbckt/200280 to your computer and use it in GitHub Desktop.
(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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment