Skip to content

Instantly share code, notes, and snippets.

@jmhdez

jmhdez/8queens-loco.clj

Last active Apr 4, 2016
Embed
What would you like to do?
;; depends on [loco "0.3.1"]
(ns loco-playground.core
(:require [loco.core :refer :all]
[loco.constraints :refer :all]))
(def queens-model
(conj
;; Variables [:x i] [:y i] para la posición de la reina i-ésima
(mapcat #(vector ($in [:x %] 0 7) ($in [:y %] 0 7)) (range 8))
;; Todas las filas deben ser distintas
($distinct (map (partial vector :x) (range 8)))
;; Todas las columnas deben ser distintas
($distinct (map (partial vector :y) (range 8)))
;; Todas las diagonales deben ser distintas
($distinct (map #($- [:x %] [:y %]) (range 8)))
;; Toas las contra-diagonales deben ser distintas
($distinct (map #($+ [:x %] [:y %]) (range 8)))))
(defn place-queens [queens]
(let [board (vec (map (fn [_] (vec (take 8 (repeat 0)))) (range 8)))]
(->> (range 8)
(reduce (fn [b i] (let [x (queens [:x i]) y (queens [:y i])]
(assoc-in b [x y] 1)))
board))))
;; Busco una solución y la pinto
(clojure.pprint/pprint (place-queens (solution queens-model)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.