Skip to content

Instantly share code, notes, and snippets.

@Heliosmaster
Forked from skuro/readme.org
Last active February 13, 2019 20:12
Show Gist options
  • Save Heliosmaster/ff37920832d942c9e711e6b347eb085d to your computer and use it in GitHub Desktop.
Save Heliosmaster/ff37920832d942c9e711e6b347eb085d to your computer and use it in GitHub Desktop.
Meetup #111 solutions
(ns oh-n0.core)
(defn transpose [board]
(apply mapv vector board))
(defn right-elems [board [i j]]
(drop (inc j) (get board i)))
(defn left-elems [board [i j]]
(reverse (take j (get board i))))
(defn indices [board]
(let [size (count board)]
(for [i (range size)
j (range size)]
[i j])))
(defn compute-neighbors [board [i j]]
(let [left (count (take-while #(not= % :r) (left-elems board [i j])))
right (count (take-while #(not= % :r) (right-elems board [i j])))
up (count (take-while #(not= % :r) (left-elems (transpose board) [j i])))
down (count (take-while #(not= % :r) (right-elems (transpose board) [j i])))]
(+ left right up down)))
(defn generate-board [size]
(let [empty-board (mapv (fn [i] (mapv (fn [j] :-) (range size))) (range size))
red-indices (vec (take (Math/floor (/ (* size size) 3))
(shuffle (indices empty-board))))
red-board (reduce (fn [acc [i j]] (assoc-in acc [i j] :r)) empty-board red-indices)
full-board (reduce (fn [acc [i j]]
(let [elem (get-in acc [i j])
x (compute-neighbors acc [i j])]
(if (= :r elem)
acc
(assoc-in acc [i j] (if (zero? x) :r x)))))
red-board (indices empty-board))]
full-board))
(def fill-cell assoc-in)
(defn init-playable-board [board]
(let [empty-indices (vec (take (Math/floor (/ (* (count board) (count board)) 2))
(shuffle (indices board))))]
(reduce (fn [acc [i j]] (assoc-in acc [i j] :-)) board empty-indices)))
(defn full-board? [board]
(zero? (count (filter #(= % :-) (mapcat identity board)))))
(defn solved? [board original-board]
(= board original-board))
(defn invalid-cells [board]
(remove (fn [idx]
(let [elem (get-in board idx)]
(or (= :r elem)
(= elem (compute-neighbors board idx)))))
(indices board)))
(defn print-board [board]
(for [row board]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment