Skip to content

Instantly share code, notes, and snippets.

@aamedina
Last active December 28, 2015 16:49
Show Gist options
  • Select an option

  • Save aamedina/7531676 to your computer and use it in GitHub Desktop.

Select an option

Save aamedina/7531676 to your computer and use it in GitHub Desktop.
(def b1 '[3 - - - - 5 - 1 -
- 7 - - - 6 - 3 -
1 - - - 9 - - - -
7 - 8 - - - - 9 -
9 - - 4 - 8 - - 2
- 6 - - - - 5 - 1
- - - - 4 - - - 6
- 4 - 7 - - - 2 -
- 2 - 6 - - - - 3])
(defn rowify
[board]
(->> board
(partition 9)
(map vec)
vec))
(defn colify
[rows]
(apply map vector rows))
(defn subgrid
[rows]
(partition 9 (for [row (range 0 9 3)
col (range 0 9 3)
x (range row (+ row 3))
y (range col (+ col 3))]
(get-in rows [x y]))))
(def logic-board #(repeatedly 81 logic/lvar))
(defn init
[[lv & lvs] [cell & cells]]
(if lv
(fresh []
(if (= '- cell)
logic/succeed
(== lv cell))
(init lvs cells))
logic/succeed))
(defn solve-logically
[board]
(let [legal-nums (fd/interval 1 9)
lvars (logic-board)
rows (rowify board)
cols (colify rows)
grids (subgrid rows)]
(logic/run 1 [q]
(init lvars board)
(logic/everyg #(fd/in % legal-nums) lvars)
(logic/everyg fd/distinct rows)
(logic/everyg fd/distinct cols)
(logic/everyg fd/distinct grids)
(== q lvars))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment