Skip to content

Instantly share code, notes, and snippets.

@ngsw-taro
Last active December 19, 2015 17:09
Show Gist options
  • Save ngsw-taro/5988944 to your computer and use it in GitHub Desktop.
Save ngsw-taro/5988944 to your computer and use it in GitHub Desktop.
Clojureの練習
(defn index-to-pos [index width] [(int (/ index width)) (rem index width)])
(defn pos [{width :width cells :cells} cell] (index-to-pos (.indexOf cells cell) width))
(defn distance [[r1 c1] [r2 c2]] (+ (Math/abs (- r1 r2)) (Math/abs (- c1 c2))))
(defn win-distance [{width :width cells :cells :as board} cell]
(distance (pos board cell) (pos {:width width :cells (range 0 (count cells))} cell)))
(defn total-win-distance [{cells :cells :as board}]
(apply + (map #(win-distance board %) cells)))
(defn cost [{count :count :as board}]
(+ count (total-win-distance board)))
(defn swap-index [cells index1 index2]
(assoc (assoc cells index1 (cells index2)) index2 (cells index1)))
(defn swap-cell [cells cell1 cell2]
(swap-index cells (.indexOf cells cell1) (.indexOf cells cell2)))
(defn move [{count :count width :width cells :cells :as board}]
(map (partial assoc {:count (inc count) :width width} :cells)
(filter #(= 1 (distance (pos board 0) (pos {:width width :cells %} 0)))
(map (partial swap-cell cells 0) cells))))
(defn sort-by-cost [boards]
(sort #(< (cost (first %1)) (cost (first %2))) boards))
(defn game [board]
(loop [queue [[board]]]
(let [current (first queue) current-board (first current)]
(if (zero? (total-win-distance current-board)) (reverse current)
(recur (sort-by-cost (concat
(map #(cons % current) (move current-board))
(rest queue))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment