Skip to content

Instantly share code, notes, and snippets.

@egri-nagy
Last active November 16, 2017 01:41
Show Gist options
  • Save egri-nagy/490571b0730e2a3dafcaa5a3d1b72261 to your computer and use it in GitHub Desktop.
Save egri-nagy/490571b0730e2a3dafcaa5a3d1b72261 to your computer and use it in GitHub Desktop.
Generating latin squares with core.logic in Clojure
;; adapted from the Sudoku solver in `The Joy of Clojure 2nd Edition' 2014 by Michal Fogus and Chris Houser, Chater 16 Thinking Programs
(require '[clojure.core.logic :as l] ;;the logic engine
'[clojure.core.logic.fd :as fd]) ;;dealing with finite domains (integer numbers)
(defn latin-squares [n num-of-sols] ;; n - size of the square, num-fo-sols - number of solutions
(let [tab (vec (repeatedly (* n n) l/lvar)) ;; n by n table of logic variables
rows (partition n tab) ;; rows of the table
cols (apply map vector rows) ;; columns of the table
points (fd/interval 0 (dec n))] ;; valid entries
(l/run num-of-sols [q]
(l/everyg (fn [x] (fd/in x points)) tab) ;; all entries are valid
(l/everyg fd/distinct rows) ;; every row has distinct entries
(l/everyg fd/distinct cols) ;; same for columns
(l/== q tab)))) ;; unification
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment