Skip to content

Instantly share code, notes, and snippets.

@featheredtoast
Last active June 10, 2018 00:30
Show Gist options
  • Save featheredtoast/4bf609355d5e49b2e4133f36ca0a98cc to your computer and use it in GitHub Desktop.
Save featheredtoast/4bf609355d5e49b2e4133f36ca0a98cc to your computer and use it in GitHub Desktop.
logic solving the mastermind thing.
(ns logic-foo.core
(:use [clojure.core.logic]
[clojure.core.logic.pldb]
[clojure.tools.macro]))
(defmacro mastermind
[spaces possibles unknown-pos known-pos]
(let [q (gensym)
arg (gensym)
syms (mapv (fn [_] (gensym)) (range spaces))]
`(run* [~q]
(fresh ~syms
~@(map (fn [sym] `(membero ~sym ~possibles)) syms)
(== ~syms ~q)
(pred ~q #(= (count (set %)) (count %))) ;;unique
~@(map (fn [ele] `(membero ~ele ~q)) unknown-pos) ;;unknown pos
~@(map (fn [[k v]] `(pred ~q (fn [~arg] (= (~arg ~k) ~v)))) known-pos) ;;known pos
))))
;;#spaces to choose, possible vals, existance vec, known position map
(mastermind 3 [1 2 3 4 5 6] [2 5] {0 3})
(ns logic-foo.core
(:use [clojure.core.logic]
[clojure.core.logic.pldb]
[clojure.tools.macro]))
(defmacro mastermind [spaces possibles]
(let [q (gensym)
syms (mapv (fn [_] (gensym)) (range spaces))]
`(run* [~q]
(fresh ~syms
~@(map (fn [sym] `(membero ~sym ~possibles)) syms)
(== ~syms ~q)
(pred ~q #(= (count (set %)) (count %))) ;;unique
(membero 2 ~q) ;;things we can find out, eg, 2 is correct, but we dont know where it is.
(membero 5 ~q) ;;things we can find out, eg, 2 is correct, but we dont know where it is.
(pred ~q #(= (% 0) 3)) ;;3 is in the first position
))))
(mastermind 3 [1 2 3 4 5 6])
(ns logic-foo.core
(:use [clojure.core.logic]
[clojure.core.logic.pldb]
[clojure.tools.macro]))
(symbol-macrolet
[_ (lvar)]
(run* [q]
(fresh [a b c possibles]
(== [1 2 3 4 5 6] possibles)
(membero a possibles)
(membero b possibles)
(membero c possibles)
(== [a b c] q)
(pred q #(= (count (set %)) (count %))) ;;unique
(membero 2 q) ;;things we can find out, eg, 2 is correct, but we dont know where it is.
(== [1 _ _] q) ;;1 is in the first position
)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment