SHARE
TWEET

Untitled

a guest Sep 17th, 2019 97 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sudoku
  2.  
  3. ```clojure
  4. (ns sudoku
  5.   (:refer-clojure :exclude [==])
  6.   (:use clojure.core.logic))
  7.  
  8. (defn get-square [rows x y]
  9.   (for [x (range x (+ x 3))
  10.         y (range y (+ y 3))]
  11.     (get-in rows [x y])))
  12.  
  13. (defn init [vars hints]
  14.   (if (seq vars)
  15.     (let [hint (first hints)]
  16.       (all
  17.         (if-not (zero? hint)
  18.           (== (first vars) hint)
  19.           succeed)
  20.         (init (next vars) (next hints))))
  21.     succeed))
  22.  
  23. (defn sudokufd [hints]
  24.   (let [vars (repeatedly 81 lvar)
  25.         rows (->> vars (partition 9) (map vec) (into []))
  26.         cols (apply map vector rows)
  27.         sqs  (for [x (range 0 9 3)
  28.                    y (range 0 9 3)]
  29.                (get-square rows x y))]
  30.     (run 1 [q]
  31.       (== q vars)
  32.       (everyg #(infd % (domain 1 2 3 4 5 6 7 8 9)) vars)
  33.       (init vars hints)
  34.       (everyg distinctfd rows)
  35.       (everyg distinctfd cols)
  36.       (everyg distinctfd sqs))))
  37.  
  38. ;; ====
  39.  
  40. (comment
  41.   (sudokufd
  42.     [0 0 3  0 2 0  6 0 0
  43.      9 0 0  3 0 5  0 0 1
  44.      0 0 1  8 0 6  4 0 0
  45.  
  46.      0 0 8  1 0 2  9 0 0
  47.      7 0 0  0 0 0  0 0 8
  48.      0 0 6  7 0 8  2 0 0
  49.  
  50.      0 0 2  6 0 9  5 0 0
  51.      8 0 0  2 0 3  0 0 9
  52.      0 0 5  0 1 0  3 0 0])
  53. )
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top