Skip to content

Instantly share code, notes, and snippets.

@Gonzih
Forked from skuro/nonograms.clj
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gonzih/bcd452a349817e285451 to your computer and use it in GitHub Desktop.
Save Gonzih/bcd452a349817e285451 to your computer and use it in GitHub Desktop.
(ns dojo-elmar.core)
(def problem
{ :size [10 10]
:rows [[] [1 1] [1] [2 1 1] [1 1 1] [1 2 1 1] [1] [1] [] []]
:cols [[] [1] [] [3] [1 1] [] [5] [1] [1 4] []] })
(def problem1x1
{:size [2 2]
:rows [[1] [1]]
:cols [[1] [1]]})
(def problem5x5
{:size [5 5]
:rows [[2] [2] [2] [3] [3 1]]
:cols [[1] [1] [3] [4] [2 2]]})
(defn compute-sum [v]
(map count (filter #(pos? (reduce + %)) (partition-by zero? v))))
(defn extract-row [bitmap size r]
(map #(get bitmap %) (range (* size r)
(* size (inc r)))))
(defn extract-coll [bitmap size c]
(map #(get bitmap %)
(map #(+ c %)
(map #(* size %)
(range 0 size)))))
(defn valid-by [{:keys [rows cols size] :as problem} result]
(let [[x y] size
verify-fn (fn [extract-fn index sum-v]
(= sum-v
(compute-sum (extract-fn result x index))))]
(let [r-rows (reduce #(and %1 %2) (map-indexed (partial verify-fn extract-row) rows))
r-cols (reduce #(and %1 %2) (map-indexed (partial verify-fn extract-coll) cols))]
(and r-rows r-cols))))
; Better to use permutations here :(
(defn result-for-number [n sq]
(let [bin-s (Integer/toBinaryString n)
s (concat (repeat (- sq (count bin-s)) \0)
bin-s)]
(vec (map #(- (int %) 48) s))))
(defn omfg []
(let [size 5
sq (* size size)
problem problem5x5
limit 8388608]
(loop [i 0]
(when (zero? (mod i 10000))
(prn i))
(let [solution (result-for-number i sq)
r (valid-by problem solution)]
(if (< i limit)
(if r
(prn "==========>" solution)
(recur (inc i)))
(prn "Reached the limit"))))))
(defn -main [] (omfg))
@fedragon
Copy link

cool code bor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment