Skip to content

Instantly share code, notes, and snippets.

@RickMoynihan
Last active January 3, 2016 22:19
Show Gist options
  • Select an option

  • Save RickMoynihan/8527928 to your computer and use it in GitHub Desktop.

Select an option

Save RickMoynihan/8527928 to your computer and use it in GitHub Desktop.
(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 ->rows [xs]
(->> xs (partition 9) (map vec) (into [])))
(defn ->cols [rows]
(apply map vector rows))
(defn ->squares [rows]
(for [x (range 0 9 3)
y (range 0 9 3)]
(get-square rows x y)))
(defn sudokufd [hints]
(let [vars (repeatedly 81 lvar)
rows (->rows vars)
cols (->cols rows)
sqs (->squares rows)]
(run-nc 1 [q]
(== q vars)
(distribute q ::l/ff)
(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))))
(defn verify [vars]
(let [rows (->rows vars)
cols (->cols rows)
sqs (->squares rows)
verify-group (fn [group]
(every? #(= (->> % (into #{}) count) 9)
group))]
(and (verify-group rows)
(verify-group cols)
(verify-group sqs))))
(def easy0
[0 0 3 0 2 0 6 0 0
9 0 0 3 0 5 0 0 1
0 0 1 8 0 6 4 0 0
0 0 8 1 0 2 9 0 0
7 0 0 0 0 0 0 0 8
0 0 6 7 0 8 2 0 0
0 0 2 6 0 9 5 0 0
8 0 0 2 0 3 0 0 9
0 0 5 0 1 0 3 0 0])
(deftest test-sudokufd
(is (-> (sudokufd easy0) first verify)))
@RickMoynihan

Copy link
Copy Markdown
Author

From the core.logic test suite.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment