Skip to content

Instantly share code, notes, and snippets.

@pbostrom
Forked from swannodette/gist:3217582
Last active December 15, 2015 23:39
Show Gist options
  • Save pbostrom/5342129 to your computer and use it in GitHub Desktop.
Save pbostrom/5342129 to your computer and use it in GitHub Desktop.
Sudoku solver via https://gist.github.com/swannodette/3217582, modified for Twitter REPL
;; works with core.logic 0.8.4
(require '[clojure.core.logic :refer :all])
(require '[clojure.core.logic.fd :as fd])
(defn get-square [rows x y]
(for [x (range x (+ x 3))
y (range y (+ y 3))]
(get-in rows [x y])))
(defn init [vars hints]
(if (seq vars)
(let [hint (first hints)]
(all
(if-not (zero? hint)
(== (first vars) hint)
succeed)
(init (next vars) (next hints))))
succeed))
(defn sudokufd [hints-str]
(let [vars (repeatedly 81 lvar)
rows (->> vars (partition 9) (map vec) (into []))
cols (apply map vector rows)
sqs (for [x (range 0 9 3)
y (range 0 9 3)]
(get-square rows x y))
hints (map #(Character/getNumericValue %) hints-str)]
(->> (run 1 [q]
(== q vars)
(everyg #(fd/in % (fd/domain 1 2 3 4 5 6 7 8 9)) vars)
(init vars hints)
(everyg fd/distinct rows)
(everyg fd/distinct cols)
(everyg fd/distinct sqs))
first (apply str))))
;; ====
(sudokufd "003020600900305001001806400008102900700000008006708200002609500800203009005010300")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment