Skip to content

Instantly share code, notes, and snippets.

@zoren
Last active December 18, 2022 21:34
Show Gist options
  • Save zoren/8bcdf0317dac4821b554b749bea9feaa to your computer and use it in GitHub Desktop.
Save zoren/8bcdf0317dac4821b554b749bea9feaa to your computer and use it in GitHub Desktop.
Solving a children's puzzle using a big gun (clojure.core.logic)
(ns logic
(:refer-clojure :exclude [==])
(:require [clojure.core.logic :refer :all])
(:require [clojure.core.logic.fd :as fd]))
;; mostly stolen from https://mattsenior.com/2014/02/using-clojures-core-logic-to-solve-simple-number-puzzles
(run* [q]
;; Create some new logic vars (lvars) for us to use in our rules
(fresh [v00 v01 v02 v03 v04
v10 v11 v12 v13 v14
v20 v21 v22 v23 v24
v30 v31 v32 v33 v34
v40 v41 v42 v43 v44]
;; Unify q with our lvars in the output format we want
(== q [[v00 v01 v02 v03 v04]
[v10 v11 v12 v13 v14]
[v20 v21 v22 v23 v24]
[v30 v31 v32 v33 v34]
[v40 v41 v42 v43 v44]])
;; State that every one of our lvars should be in the range 1-25
(fd/in v00 v01 v02 v03 v04
v10 v11 v12 v13 v14
v20 v21 v22 v23 v24
v30 v31 v32 v33 v34
v40 v41 v42 v43 v44 (fd/interval 1 25))
;; State that each of our lvars should be unique
(fd/distinct [v00 v01 v02 v03 v04
v10 v11 v12 v13 v14
v20 v21 v22 v23 v24
v30 v31 v32 v33 v34
v40 v41 v42 v43 v44])
;; fd/eq is just a helper to allow us to use standard Clojure
;; operators like + instead of fd/+
(fd/eq
;; Horizontal conditions for the puzzle
(= (+ v00 v01 v02 v03 v04) 65)
(= (+ v10 v11 v12 v13 v14) 65)
(= (+ v20 v21 v22 v23 v24) 65)
(= (+ v30 v31 v32 v33 v34) 65)
(= (+ v40 v41 v42 v43 v44) 65)
;; Vertical conditions for the puzzle
(= (+ v00 v10 v20 v30 v40) 65)
(= (+ v01 v11 v21 v31 v41) 65)
(= (+ v02 v12 v22 v32 v42) 65)
(= (+ v03 v13 v23 v33 v43) 65)
(= (+ v04 v14 v24 v34 v44) 65)
;; Diagonal conditions for the puzzle
(= (+ v00 v11 v22 v33 v44) 65)
(= (+ v04 v13 v22 v31 v40) 65)
;; input
(= v02 1)
(= v04 7)
(= v10 16)
(= v14 3)
(= v21 5)
(= v22 18)
(= v31 21)
(= v44 11))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment