Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,41 +1,24 @@
(ns sudoku
(:use [clojure.contrib.math :only (sqrt)]))
(ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn print-grid [grid]
(doseq [y (range (count grid))]
(doseq [x (range (count grid))]
(print (retrieve grid x y) " "))
(println))
(println))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn retrieve [grid x y]
(get (get grid y) x))
(defn store [grid x y n]
(assoc grid y (assoc (get grid y) x n)))
(defn coordinates [grid x y]
(let [n (sqrt (count grid))
zx (* n (quot x n))
zy (* n (quot y n))]
(for [x (range zx (+ zx n)) y (range zy (+ zy n))]
[x y])))
(defn compatible? [grid x y n]
(or
(= n (retrieve grid x y))
(and
(zero? (retrieve grid x y))
(every? #(and (not= n (retrieve grid % y)) (not= n (retrieve grid x %))) (range (count grid)))
(every? #(not= n (retrieve grid (first %) (second %))) (coordinates grid x y)))))
(defn solve [grid x y]
(let [m (count grid)]
(if (= y m)
(print-grid grid)
(doseq [n (range 1 (inc m))]
(when (compatible? grid x y n)
(let [new-grid (store grid x y n)]
(if (= x (dec m))
(solve new-grid 0 (inc y))
(solve new-grid (inc x) y))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))

View file

@ -1,13 +1,13 @@
sudoku> (solve [[3 9 4 0 0 2 6 7 0]
[0 0 0 3 0 0 4 0 0]
[5 0 0 6 9 0 0 2 0]
[0 4 5 0 0 0 9 0 0]
[6 0 0 0 0 0 0 0 7]
[0 0 7 0 0 0 5 8 0]
[0 1 0 0 6 7 0 0 8]
[0 0 9 0 0 8 0 0 0]
[0 2 6 4 0 0 7 3 5]]
0 0)
sudoku>(cl-format true "~{~{~a~^ ~}~%~}"
(solve [[3 9 4 0 0 2 6 7 0]
[0 0 0 3 0 0 4 0 0]
[5 0 0 6 9 0 0 2 0]
[0 4 5 0 0 0 9 0 0]
[6 0 0 0 0 0 0 0 7]
[0 0 7 0 0 0 5 8 0]
[0 1 0 0 6 7 0 0 8]
[0 0 9 0 0 8 0 0 0]
[0 2 6 4 0 0 7 3 5]])
3 9 4 8 5 2 6 7 1
2 6 8 3 7 1 4 5 9
5 7 1 6 9 4 8 2 3