Last active
August 29, 2015 14:05
-
-
Save tomasv/59f914e9c30be0c5b9b2 to your computer and use it in GitHub Desktop.
Find a cross of zeroes in a sea of pluses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns zero-island.core) | |
(def problem "+++0++\n++000+\n+++0++\n++++++") | |
(def ^:private value-encoding {\0 :zero \+ :plus}) | |
(defn- split-lines [problem] | |
(clojure.string/split problem #"\s+")) | |
(defn- indexed-seq [s] | |
(map-indexed vector s)) | |
(defn- build-cell [column-index [row-index value]] | |
(let [coded-value (value-encoding value)] | |
{:value coded-value | |
:x row-index | |
:y column-index})) | |
(defn- indexed-line->cells [[column-index line]] | |
(let [values (vec line)] | |
(map (partial build-cell column-index) (indexed-seq values)))) | |
(defn- indexed-lines->cells [indexed-lines] | |
(mapcat indexed-line->cells indexed-lines)) | |
(defn- string->cells [string] | |
(-> string | |
split-lines | |
indexed-seq | |
indexed-lines->cells)) | |
(defn- cross-part? [{:keys [value]}] (= value :zero)) | |
(defn- cell-at? [{:keys [x y]} x' y'] | |
(and (= x x') (= y y'))) | |
(defn- find-cells-at [cells {:keys [x y]}] | |
(filter #(cell-at? % x y) cells)) | |
(defn- find-cells [cells coordinates] | |
(mapcat (partial find-cells-at cells) coordinates)) | |
(defn- cross-corners [cells {:keys [x y]}] | |
(let [coordinates [{:x x :y (dec y)} | |
{:x x :y (inc y)} | |
{:x (inc x) :y y} | |
{:x (dec x) :y y}]] | |
(find-cells cells coordinates))) | |
(defn- center? [cells cell] | |
(let [corners (cross-corners cells cell)] | |
(and | |
(= 4 (count corners)) | |
(every? cross-part? corners)))) | |
(defn- center-candidates [cells] | |
(filter cross-part? cells)) | |
(defn- find-cross-centers [cells] | |
(let [candidates (center-candidates cells)] | |
(filter (partial center? cells) candidates))) | |
(defn solve-cross-problem [string] | |
(find-cross-centers (string->cells string))) | |
(solve-cross-problem problem) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment