Skip to content

Instantly share code, notes, and snippets.

@dra1n
Created March 13, 2021 05:13
Show Gist options
  • Select an option

  • Save dra1n/326076733eef49382e677f6247a2098b to your computer and use it in GitHub Desktop.

Select an option

Save dra1n/326076733eef49382e677f6247a2098b to your computer and use it in GitHub Desktop.
(ns number-puzzles.core
(:refer-clojure :exclude [==]) ;; Prevent ns conflict
(:require [clojure.core.logic :refer :all]))
(run* [q]
(fresh [a b c variants]
(== [0 1 2 3 4 6 7 8] variants)
(membero a variants)
(membero b variants)
(membero c variants)
;; [6 8 2] One digit is right and in its place
(fresh [comb]
(== comb [6 8 2])
(conde [(== [a 8 2] comb)
(nafc membero b comb)
(nafc membero c comb)]
[(== [6 b 2] comb)
(nafc membero a comb)
(nafc membero c comb)]
[(== [6 8 c] comb)
(nafc membero b comb)
(nafc membero a comb)]))
;; [6 1 4] One digit is right but in the wrong place
(fresh [comb]
(== comb [6 1 4])
(conde [(== [6 a 4] comb)]
[(== [6 1 a] comb)]
[(== [b 1 4] comb)]
[(== [6 1 b] comb)]
[(== [c 1 4] comb)]
[(== [6 c 4] comb)]))
;; [2 0 6] Two digits are right but both are in the wrong place
(fresh [comb]
(== comb [2 0 6])
(conde [(== [2 a b] comb)]
[(== [2 c b] comb)]
[(== [2 c a] comb)]
[(== [c 0 b] comb)]
[(== [b 0 a] comb)]
[(== [c 0 a] comb)]
[(== [c a 6] comb)]
[(== [b c 6] comb)]
[(== [b a 6] comb)]))
;; [7 3 8] All digits are wrong
(fresh [comb]
(== comb [7 3 8])
(nafc membero a comb)
(nafc membero b comb)
(nafc membero c comb))
;; [3 8 0] One digit is right but in the wrong place
(fresh [comb]
(== comb [3 8 0])
(conde [(== [3 a 0] comb)]
[(== [3 8 a] comb)]
[(== [b 8 0] comb)]
[(== [3 8 b] comb)]
[(== [c 8 0] comb)]
[(== [3 c 0] comb)]))
(== q [a b c])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment