diff --git a/src/aichallenge/bot.clj b/src/aichallenge/bot.clj index e8a035c..26aedad 100644 --- a/src/aichallenge/bot.clj +++ b/src/aichallenge/bot.clj @@ -2,7 +2,8 @@ (:require (aichallenge [ant :as ant] [matrix :as m] - [fow :as fow]))) + [fow :as fow] + [collisions :as cs]))) (defn init-bot [{:keys [rows cols viewradius2]}] (let [visible-positions (fow/visibility-pattern viewradius2 rows cols)] @@ -14,8 +15,11 @@ (m/pr-matrix knowledge #(if (zero? %) \# \space)) {:knowledge (fow/update-visibilities knowledge (mapcat visible-positions (ant/my-ants state))) - :moves (for [ant (:ants state) - :let [dir (first (filter #(ant/valid-move? state ant %) - [:north :east :west :south]))] - :when dir] - [ant dir])})})) + :moves (->> (for [ant (:ants state) + :let [dir (first (filter #(ant/valid-move? state ant %) + [:north :east :west :south]))] + :when dir] + [ant dir]) + (cs/fix-collisions {}))})})) + + diff --git a/src/aichallenge/collisions.clj b/src/aichallenge/collisions.clj new file mode 100644 index 0000000..3871ab4 --- /dev/null +++ b/src/aichallenge/collisions.clj @@ -0,0 +1,55 @@ +(ns aichallenge.collisions + (:use [clojure.pprint :only (pprint)] + [clojure.set :only (difference)]) + (:require [aichallenge.ant :as ant])) + +(defn fpprint [filename data] + (spit (java.io.File. filename) + (with-out-str (pprint data)))) + +(defn init-matrix [x y] + (letfn [(row [] (vec (take x (repeat 0))))] + (vec (repeatedly y row)))) + +(defn collisions [moves] + (loop [m {} + ms moves] + (if (seq ms) + (recur (let [move (first ms) + next-loc (apply ant/move-ant move)] + (if (m next-loc) + (update-in m [next-loc] conj move) + (assoc m next-loc [move]))) + (next ms)) + m))) + +(def directions #{:north :south :east :west}) + +(defn find-alternative [m ant dirs] + (let [poss (map (fn [ant dir] + [ant dir (ant/move-ant ant dir)]) + (repeat ant) + dirs)] + (first (remove (fn [[_ _ next-move]] (m next-move)) + poss)))) + + +(defn all-alternatives [collisions] + (for [collision collisions + :let [moves (val collision)] + :when (> (count moves) 1) + [ant dir] moves] + (find-alternative collisions ant (difference directions #{dir})))) + +(defn fix-collisions [matrix moves] + (let [cs (collisions moves) + alts (reduce (fn [m [ant dir _]] + (assoc m ant dir)) {} + (all-alternatives cs))] + (for [[ant dir] moves] + [ant (if-let [new-dir (alts ant)] + new-dir + dir)]))) + +#_(zipmap (map first moves) + (map second moves))