n-puzzle in ClojurescriptEight queens puzzlePerformance concerns when solving sliding-tile-puzzle via A* algorithm

aging parents with no investments

Are white and non-white police officers equally likely to kill black suspects?

Need help identifying/translating a plaque in Tangier, Morocco

How to move the player while also allowing forces to affect it

Check if two datetimes are between two others

How to answer pointed "are you quitting" questioning when I don't want them to suspect

COUNT(*) or MAX(id) - which is faster?

What is the command to reset a PC without deleting any files

Domain expired, GoDaddy holds it and is asking more money

Is Social Media Science Fiction?

Could Giant Ground Sloths have been a good pack animal for the ancient Mayans?

Why is the design of haulage companies so “special”?

Is this food a bread or a loaf?

Information to fellow intern about hiring?

Why doesn't a const reference extend the life of a temporary object passed via a function?

What does it exactly mean if a random variable follows a distribution

Email Account under attack (really) - anything I can do?

"My colleague's body is amazing"

What is the meaning of "of trouble" in the following sentence?

LWC and complex parameters

extract characters between two commas?

Doomsday-clock for my fantasy planet

When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?

Is it legal to have the "// (c) 2019 John Smith" header in all files when there are hundreds of contributors?



n-puzzle in Clojurescript


Eight queens puzzlePerformance concerns when solving sliding-tile-puzzle via A* algorithm






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0












$begingroup$


I'm in the process of creating a n-puzzle solver in Clojurescript. I have the basic model up and running and can move tiles on the screen. I plan to implement A* or such an algorithm to solve a given puzzle. Before I do that, I welcome any general comments for improving the quality of the code right now.



I am just pasting the most important files only here. The entire repo is here



puzzle.cljs



 (ns npuzzle.puzzle
(:require [cljs.test :refer-macros [deftest testing is run-tests]]
[clojure.zip :as zip]))

(defn get-tiles [puzzle] (nth puzzle 0))
(defn get-size [puzzle] (nth puzzle 1))

(defn set-tiles [puzzle tiles] (assoc puzzle 0 tiles))

(defn make-puzzle
([size]
[(conj (vec (range 1 (* size size))) :space) size])
([tiles size]
[tiles size]))

(defn index->row-col [puzzle index]
(let [size (get-size puzzle)]
[(quot index size) (mod index size)]))

(defn row-col->index [puzzle [row col]]
(let [size (get-size puzzle)]
(+ (* row size) col)))

(defn get-tile [puzzle [row col]]
((get-tiles puzzle) (+ (* row (get-size puzzle)) col)))

(defn get-index-of-space [puzzle]
(.indexOf (get-tiles puzzle) :space))

(defn get-space-coords [puzzle]
(index->row-col puzzle (get-index-of-space puzzle)))

(defn is-space? [puzzle coords]
(= :space (get-tile puzzle coords)))

(defn valid-coords? [puzzle [row col]]
(let [size (get-size puzzle)]
(and (>= row 0) (>= col 0)
(< row size) (< col size))))

(defn get-adjacent-coords [puzzle [row col]]
(->> '([0 1] [-1 0] [0 -1] [1 0]) ;;'
(map (fn [[dr dc]]
[(+ row dr) (+ col dc)]))
(filter #(valid-coords? puzzle %))))

(defn inversions [puzzle]
(let [size (get-size puzzle)
tiles (get-tiles puzzle)
inversions-fn
(fn [remaining-tiles found-tiles inversions]
(if-let [i (first remaining-tiles)]
(recur (rest remaining-tiles)
(conj found-tiles i)
(+ inversions (- (dec i) (count (filter found-tiles (range i))))))
inversions))]
(inversions-fn (remove #:space tiles) # 0)))

(defn is-solvable? [puzzle]
(let [inv-cnt (inversions puzzle)
size (get-size puzzle)
[row col] (get-space-coords puzzle)]
(if (odd? size)
(even? inv-cnt)
(if (even? (- size row))
(odd? inv-cnt)
(even? inv-cnt)))))

(defn can-move? [puzzle coords]
;;Check if any one of the adjacent tiles is the space.
(->> (get-adjacent-coords puzzle coords)
(filter #(is-space? puzzle %))
(first)))

(defn swap-tiles [puzzle coord1 coord2]
(let [index1 (row-col->index puzzle coord1)
index2 (row-col->index puzzle coord2)
tile1 (get-tile puzzle coord1)
tile2 (get-tile puzzle coord2)
tiles (get-tiles puzzle)]
(set-tiles puzzle
(-> tiles
(assoc index1 tile2)
(assoc index2 tile1)))))

(defn move [puzzle coords]
(if (can-move? puzzle coords)
(swap-tiles puzzle coords (get-space-coords puzzle))
puzzle))

(defn random-move [puzzle]
(let [space-coords (get-space-coords puzzle)
movable-tiles (get-adjacent-coords puzzle space-coords)
random-movable-tile (nth movable-tiles (rand-int (count movable-tiles)))]
(move puzzle random-movable-tile)))

(defn shuffle-puzzle
"Shuffles by moving a random steps"
([puzzle]
(let [num-moves (+ 100 (rand 200))]
(shuffle-puzzle puzzle num-moves)))
([puzzle num-moves]
(if (> num-moves 0)
(recur (random-move puzzle) (dec num-moves))
puzzle)))


puzzle_test.cljs



(ns npuzzle.puzzle-test
(:require [cljs.test :refer-macros [deftest testing is run-tests]]
[npuzzle.puzzle :as pzl]))

(deftest puzzle-tests
(let [p1 (pzl/make-puzzle 3)]
(testing "make-puzzle"
(is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles p1)))
(is (= 3 (pzl/get-size p1))))
(testing "get-tile"
(is (= 1 (pzl/get-tile p1 [0 0])))
(is (= 2 (pzl/get-tile p1 [0 1])))
(is (= 5 (pzl/get-tile p1 [1 1]))))
(testing "get-index-of-space"
(is (= 8 (pzl/get-index-of-space p1))))
(testing "get-space-coords"
(is (= [2 2] (pzl/get-space-coords p1))))
(testing "is-space?"
(is (pzl/is-space? p1 [2 2]))
(is (not (pzl/is-space? p1 [2 1]))))
(testing "index->row-col"
(is (= [1 1] (pzl/index->row-col p1 4)))
(is (= [2 3] (pzl/index->row-col (pzl/make-puzzle 5) 13))))
(testing "row-col->index"
(is (= 4 (pzl/row-col->index p1 [1 1])))
(is (= 13 (pzl/row-col->index (pzl/make-puzzle 5) [2 3]))))
(testing "valid-coords?"
(is (pzl/valid-coords? p1 [1 1]))
(is (not (pzl/valid-coords? p1 [2 3]))))
(testing "get-adjacent-coords"
(is (= #[0 1] [1 0] [1 2] [2 1] (into # (pzl/get-adjacent-coords p1 [1 1]))))
(is (= #[0 1] [1 0] (into # (pzl/get-adjacent-coords p1 [0 0])))))
(testing "can-move?"
(is (pzl/can-move? p1 [1 2]))
(is (pzl/can-move? p1 [2 1]))
(is (not (pzl/can-move? p1 [1 1]))))
(testing "move"
(is (= [1 2 3 4 5 :space 7 8 6] (pzl/get-tiles (pzl/move p1 [1 2]))))
(is (= [1 2 3 4 :space 5 7 8 6] (pzl/get-tiles (pzl/move (pzl/move p1 [1 2]) [1 1]))))
(is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles (pzl/move p1 [0 1])))))
(testing "inversions"
(is (= 10 (pzl/inversions (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3))))
(is (= 41 (pzl/inversions (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4))))
(is (= 62 (pzl/inversions (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4))))
(is (= 56 (pzl/inversions (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
(testing "is-solvable?"
(is (pzl/is-solvable? (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3)))
(is (pzl/is-solvable? (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4)))
(is (pzl/is-solvable? (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4)))
(is (not (pzl/is-solvable? (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
(testing "shuffle-puzzle"
(is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 4))))
(is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 6))))
(is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 9))))
(is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 3)) (pzl/make-puzzle 3)))
(is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 8)) (pzl/make-puzzle 8))))))

(run-tests)


views.cljs



(ns npuzzle.views
(:require
[re-frame.core :as re-frame]
[npuzzle.subs :as subs]
[npuzzle.events :as ev]))

(defn- on-puzzle-size-changed [e]
(re-frame/dispatch [::ev/change-puzzle-size (int (-> e .-target .-value))]))

(defn- on-tile-mouse-down [e]
(let [idx (.getAttribute (-> e .-target) "data-tileindex")]
(re-frame/dispatch [::ev/move-tile (int idx)])))

(defn- tile-div [idx tile]
[:div :style :text-align :center
:padding "15px"
:font-size "20px"
:border (if (not= :space tile) "1px solid black" :none)
:background (if (not= :space tile) :lightblue nil)
:height "25px"
:width "25px"
;;cursor = default for disabling caret on hover over text
:cursor :default
:onMouseDown on-tile-mouse-down
:data-tileindex idx
(if (= :space tile)
" "
tile)])

(defn- tiles-container [puzzle size tile-fn]
(into [:div :style :display :inline-grid
:grid-template-columns (apply str (repeat size "auto "))
:grid-gap "2px"
:border "2px solid black"]
(map-indexed
(fn [idx tile]
(tile-fn idx tile)) puzzle)))

(defn main-panel []
(let [name (re-frame/subscribe [::subs/name])
sizes (re-frame/subscribe [::subs/size-choices])
current-size (re-frame/subscribe [::subs/puzzle-size])
puzzle (re-frame/subscribe [::subs/puzzle])]
[:div
[:h1 "Hello to " @name]
[:div
:style :padding "10px"
(into [:select :name "puzzle-size"
:on-change on-puzzle-size-changed
:defaultValue @current-size]
(for [size @sizes]
(into [:option :value size size])))]
(tiles-container @puzzle @current-size tile-div)]))








share









$endgroup$


















    0












    $begingroup$


    I'm in the process of creating a n-puzzle solver in Clojurescript. I have the basic model up and running and can move tiles on the screen. I plan to implement A* or such an algorithm to solve a given puzzle. Before I do that, I welcome any general comments for improving the quality of the code right now.



    I am just pasting the most important files only here. The entire repo is here



    puzzle.cljs



     (ns npuzzle.puzzle
    (:require [cljs.test :refer-macros [deftest testing is run-tests]]
    [clojure.zip :as zip]))

    (defn get-tiles [puzzle] (nth puzzle 0))
    (defn get-size [puzzle] (nth puzzle 1))

    (defn set-tiles [puzzle tiles] (assoc puzzle 0 tiles))

    (defn make-puzzle
    ([size]
    [(conj (vec (range 1 (* size size))) :space) size])
    ([tiles size]
    [tiles size]))

    (defn index->row-col [puzzle index]
    (let [size (get-size puzzle)]
    [(quot index size) (mod index size)]))

    (defn row-col->index [puzzle [row col]]
    (let [size (get-size puzzle)]
    (+ (* row size) col)))

    (defn get-tile [puzzle [row col]]
    ((get-tiles puzzle) (+ (* row (get-size puzzle)) col)))

    (defn get-index-of-space [puzzle]
    (.indexOf (get-tiles puzzle) :space))

    (defn get-space-coords [puzzle]
    (index->row-col puzzle (get-index-of-space puzzle)))

    (defn is-space? [puzzle coords]
    (= :space (get-tile puzzle coords)))

    (defn valid-coords? [puzzle [row col]]
    (let [size (get-size puzzle)]
    (and (>= row 0) (>= col 0)
    (< row size) (< col size))))

    (defn get-adjacent-coords [puzzle [row col]]
    (->> '([0 1] [-1 0] [0 -1] [1 0]) ;;'
    (map (fn [[dr dc]]
    [(+ row dr) (+ col dc)]))
    (filter #(valid-coords? puzzle %))))

    (defn inversions [puzzle]
    (let [size (get-size puzzle)
    tiles (get-tiles puzzle)
    inversions-fn
    (fn [remaining-tiles found-tiles inversions]
    (if-let [i (first remaining-tiles)]
    (recur (rest remaining-tiles)
    (conj found-tiles i)
    (+ inversions (- (dec i) (count (filter found-tiles (range i))))))
    inversions))]
    (inversions-fn (remove #:space tiles) # 0)))

    (defn is-solvable? [puzzle]
    (let [inv-cnt (inversions puzzle)
    size (get-size puzzle)
    [row col] (get-space-coords puzzle)]
    (if (odd? size)
    (even? inv-cnt)
    (if (even? (- size row))
    (odd? inv-cnt)
    (even? inv-cnt)))))

    (defn can-move? [puzzle coords]
    ;;Check if any one of the adjacent tiles is the space.
    (->> (get-adjacent-coords puzzle coords)
    (filter #(is-space? puzzle %))
    (first)))

    (defn swap-tiles [puzzle coord1 coord2]
    (let [index1 (row-col->index puzzle coord1)
    index2 (row-col->index puzzle coord2)
    tile1 (get-tile puzzle coord1)
    tile2 (get-tile puzzle coord2)
    tiles (get-tiles puzzle)]
    (set-tiles puzzle
    (-> tiles
    (assoc index1 tile2)
    (assoc index2 tile1)))))

    (defn move [puzzle coords]
    (if (can-move? puzzle coords)
    (swap-tiles puzzle coords (get-space-coords puzzle))
    puzzle))

    (defn random-move [puzzle]
    (let [space-coords (get-space-coords puzzle)
    movable-tiles (get-adjacent-coords puzzle space-coords)
    random-movable-tile (nth movable-tiles (rand-int (count movable-tiles)))]
    (move puzzle random-movable-tile)))

    (defn shuffle-puzzle
    "Shuffles by moving a random steps"
    ([puzzle]
    (let [num-moves (+ 100 (rand 200))]
    (shuffle-puzzle puzzle num-moves)))
    ([puzzle num-moves]
    (if (> num-moves 0)
    (recur (random-move puzzle) (dec num-moves))
    puzzle)))


    puzzle_test.cljs



    (ns npuzzle.puzzle-test
    (:require [cljs.test :refer-macros [deftest testing is run-tests]]
    [npuzzle.puzzle :as pzl]))

    (deftest puzzle-tests
    (let [p1 (pzl/make-puzzle 3)]
    (testing "make-puzzle"
    (is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles p1)))
    (is (= 3 (pzl/get-size p1))))
    (testing "get-tile"
    (is (= 1 (pzl/get-tile p1 [0 0])))
    (is (= 2 (pzl/get-tile p1 [0 1])))
    (is (= 5 (pzl/get-tile p1 [1 1]))))
    (testing "get-index-of-space"
    (is (= 8 (pzl/get-index-of-space p1))))
    (testing "get-space-coords"
    (is (= [2 2] (pzl/get-space-coords p1))))
    (testing "is-space?"
    (is (pzl/is-space? p1 [2 2]))
    (is (not (pzl/is-space? p1 [2 1]))))
    (testing "index->row-col"
    (is (= [1 1] (pzl/index->row-col p1 4)))
    (is (= [2 3] (pzl/index->row-col (pzl/make-puzzle 5) 13))))
    (testing "row-col->index"
    (is (= 4 (pzl/row-col->index p1 [1 1])))
    (is (= 13 (pzl/row-col->index (pzl/make-puzzle 5) [2 3]))))
    (testing "valid-coords?"
    (is (pzl/valid-coords? p1 [1 1]))
    (is (not (pzl/valid-coords? p1 [2 3]))))
    (testing "get-adjacent-coords"
    (is (= #[0 1] [1 0] [1 2] [2 1] (into # (pzl/get-adjacent-coords p1 [1 1]))))
    (is (= #[0 1] [1 0] (into # (pzl/get-adjacent-coords p1 [0 0])))))
    (testing "can-move?"
    (is (pzl/can-move? p1 [1 2]))
    (is (pzl/can-move? p1 [2 1]))
    (is (not (pzl/can-move? p1 [1 1]))))
    (testing "move"
    (is (= [1 2 3 4 5 :space 7 8 6] (pzl/get-tiles (pzl/move p1 [1 2]))))
    (is (= [1 2 3 4 :space 5 7 8 6] (pzl/get-tiles (pzl/move (pzl/move p1 [1 2]) [1 1]))))
    (is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles (pzl/move p1 [0 1])))))
    (testing "inversions"
    (is (= 10 (pzl/inversions (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3))))
    (is (= 41 (pzl/inversions (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4))))
    (is (= 62 (pzl/inversions (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4))))
    (is (= 56 (pzl/inversions (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
    (testing "is-solvable?"
    (is (pzl/is-solvable? (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3)))
    (is (pzl/is-solvable? (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4)))
    (is (pzl/is-solvable? (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4)))
    (is (not (pzl/is-solvable? (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
    (testing "shuffle-puzzle"
    (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 4))))
    (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 6))))
    (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 9))))
    (is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 3)) (pzl/make-puzzle 3)))
    (is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 8)) (pzl/make-puzzle 8))))))

    (run-tests)


    views.cljs



    (ns npuzzle.views
    (:require
    [re-frame.core :as re-frame]
    [npuzzle.subs :as subs]
    [npuzzle.events :as ev]))

    (defn- on-puzzle-size-changed [e]
    (re-frame/dispatch [::ev/change-puzzle-size (int (-> e .-target .-value))]))

    (defn- on-tile-mouse-down [e]
    (let [idx (.getAttribute (-> e .-target) "data-tileindex")]
    (re-frame/dispatch [::ev/move-tile (int idx)])))

    (defn- tile-div [idx tile]
    [:div :style :text-align :center
    :padding "15px"
    :font-size "20px"
    :border (if (not= :space tile) "1px solid black" :none)
    :background (if (not= :space tile) :lightblue nil)
    :height "25px"
    :width "25px"
    ;;cursor = default for disabling caret on hover over text
    :cursor :default
    :onMouseDown on-tile-mouse-down
    :data-tileindex idx
    (if (= :space tile)
    " "
    tile)])

    (defn- tiles-container [puzzle size tile-fn]
    (into [:div :style :display :inline-grid
    :grid-template-columns (apply str (repeat size "auto "))
    :grid-gap "2px"
    :border "2px solid black"]
    (map-indexed
    (fn [idx tile]
    (tile-fn idx tile)) puzzle)))

    (defn main-panel []
    (let [name (re-frame/subscribe [::subs/name])
    sizes (re-frame/subscribe [::subs/size-choices])
    current-size (re-frame/subscribe [::subs/puzzle-size])
    puzzle (re-frame/subscribe [::subs/puzzle])]
    [:div
    [:h1 "Hello to " @name]
    [:div
    :style :padding "10px"
    (into [:select :name "puzzle-size"
    :on-change on-puzzle-size-changed
    :defaultValue @current-size]
    (for [size @sizes]
    (into [:option :value size size])))]
    (tiles-container @puzzle @current-size tile-div)]))








    share









    $endgroup$














      0












      0








      0





      $begingroup$


      I'm in the process of creating a n-puzzle solver in Clojurescript. I have the basic model up and running and can move tiles on the screen. I plan to implement A* or such an algorithm to solve a given puzzle. Before I do that, I welcome any general comments for improving the quality of the code right now.



      I am just pasting the most important files only here. The entire repo is here



      puzzle.cljs



       (ns npuzzle.puzzle
      (:require [cljs.test :refer-macros [deftest testing is run-tests]]
      [clojure.zip :as zip]))

      (defn get-tiles [puzzle] (nth puzzle 0))
      (defn get-size [puzzle] (nth puzzle 1))

      (defn set-tiles [puzzle tiles] (assoc puzzle 0 tiles))

      (defn make-puzzle
      ([size]
      [(conj (vec (range 1 (* size size))) :space) size])
      ([tiles size]
      [tiles size]))

      (defn index->row-col [puzzle index]
      (let [size (get-size puzzle)]
      [(quot index size) (mod index size)]))

      (defn row-col->index [puzzle [row col]]
      (let [size (get-size puzzle)]
      (+ (* row size) col)))

      (defn get-tile [puzzle [row col]]
      ((get-tiles puzzle) (+ (* row (get-size puzzle)) col)))

      (defn get-index-of-space [puzzle]
      (.indexOf (get-tiles puzzle) :space))

      (defn get-space-coords [puzzle]
      (index->row-col puzzle (get-index-of-space puzzle)))

      (defn is-space? [puzzle coords]
      (= :space (get-tile puzzle coords)))

      (defn valid-coords? [puzzle [row col]]
      (let [size (get-size puzzle)]
      (and (>= row 0) (>= col 0)
      (< row size) (< col size))))

      (defn get-adjacent-coords [puzzle [row col]]
      (->> '([0 1] [-1 0] [0 -1] [1 0]) ;;'
      (map (fn [[dr dc]]
      [(+ row dr) (+ col dc)]))
      (filter #(valid-coords? puzzle %))))

      (defn inversions [puzzle]
      (let [size (get-size puzzle)
      tiles (get-tiles puzzle)
      inversions-fn
      (fn [remaining-tiles found-tiles inversions]
      (if-let [i (first remaining-tiles)]
      (recur (rest remaining-tiles)
      (conj found-tiles i)
      (+ inversions (- (dec i) (count (filter found-tiles (range i))))))
      inversions))]
      (inversions-fn (remove #:space tiles) # 0)))

      (defn is-solvable? [puzzle]
      (let [inv-cnt (inversions puzzle)
      size (get-size puzzle)
      [row col] (get-space-coords puzzle)]
      (if (odd? size)
      (even? inv-cnt)
      (if (even? (- size row))
      (odd? inv-cnt)
      (even? inv-cnt)))))

      (defn can-move? [puzzle coords]
      ;;Check if any one of the adjacent tiles is the space.
      (->> (get-adjacent-coords puzzle coords)
      (filter #(is-space? puzzle %))
      (first)))

      (defn swap-tiles [puzzle coord1 coord2]
      (let [index1 (row-col->index puzzle coord1)
      index2 (row-col->index puzzle coord2)
      tile1 (get-tile puzzle coord1)
      tile2 (get-tile puzzle coord2)
      tiles (get-tiles puzzle)]
      (set-tiles puzzle
      (-> tiles
      (assoc index1 tile2)
      (assoc index2 tile1)))))

      (defn move [puzzle coords]
      (if (can-move? puzzle coords)
      (swap-tiles puzzle coords (get-space-coords puzzle))
      puzzle))

      (defn random-move [puzzle]
      (let [space-coords (get-space-coords puzzle)
      movable-tiles (get-adjacent-coords puzzle space-coords)
      random-movable-tile (nth movable-tiles (rand-int (count movable-tiles)))]
      (move puzzle random-movable-tile)))

      (defn shuffle-puzzle
      "Shuffles by moving a random steps"
      ([puzzle]
      (let [num-moves (+ 100 (rand 200))]
      (shuffle-puzzle puzzle num-moves)))
      ([puzzle num-moves]
      (if (> num-moves 0)
      (recur (random-move puzzle) (dec num-moves))
      puzzle)))


      puzzle_test.cljs



      (ns npuzzle.puzzle-test
      (:require [cljs.test :refer-macros [deftest testing is run-tests]]
      [npuzzle.puzzle :as pzl]))

      (deftest puzzle-tests
      (let [p1 (pzl/make-puzzle 3)]
      (testing "make-puzzle"
      (is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles p1)))
      (is (= 3 (pzl/get-size p1))))
      (testing "get-tile"
      (is (= 1 (pzl/get-tile p1 [0 0])))
      (is (= 2 (pzl/get-tile p1 [0 1])))
      (is (= 5 (pzl/get-tile p1 [1 1]))))
      (testing "get-index-of-space"
      (is (= 8 (pzl/get-index-of-space p1))))
      (testing "get-space-coords"
      (is (= [2 2] (pzl/get-space-coords p1))))
      (testing "is-space?"
      (is (pzl/is-space? p1 [2 2]))
      (is (not (pzl/is-space? p1 [2 1]))))
      (testing "index->row-col"
      (is (= [1 1] (pzl/index->row-col p1 4)))
      (is (= [2 3] (pzl/index->row-col (pzl/make-puzzle 5) 13))))
      (testing "row-col->index"
      (is (= 4 (pzl/row-col->index p1 [1 1])))
      (is (= 13 (pzl/row-col->index (pzl/make-puzzle 5) [2 3]))))
      (testing "valid-coords?"
      (is (pzl/valid-coords? p1 [1 1]))
      (is (not (pzl/valid-coords? p1 [2 3]))))
      (testing "get-adjacent-coords"
      (is (= #[0 1] [1 0] [1 2] [2 1] (into # (pzl/get-adjacent-coords p1 [1 1]))))
      (is (= #[0 1] [1 0] (into # (pzl/get-adjacent-coords p1 [0 0])))))
      (testing "can-move?"
      (is (pzl/can-move? p1 [1 2]))
      (is (pzl/can-move? p1 [2 1]))
      (is (not (pzl/can-move? p1 [1 1]))))
      (testing "move"
      (is (= [1 2 3 4 5 :space 7 8 6] (pzl/get-tiles (pzl/move p1 [1 2]))))
      (is (= [1 2 3 4 :space 5 7 8 6] (pzl/get-tiles (pzl/move (pzl/move p1 [1 2]) [1 1]))))
      (is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles (pzl/move p1 [0 1])))))
      (testing "inversions"
      (is (= 10 (pzl/inversions (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3))))
      (is (= 41 (pzl/inversions (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4))))
      (is (= 62 (pzl/inversions (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4))))
      (is (= 56 (pzl/inversions (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
      (testing "is-solvable?"
      (is (pzl/is-solvable? (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3)))
      (is (pzl/is-solvable? (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4)))
      (is (pzl/is-solvable? (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4)))
      (is (not (pzl/is-solvable? (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
      (testing "shuffle-puzzle"
      (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 4))))
      (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 6))))
      (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 9))))
      (is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 3)) (pzl/make-puzzle 3)))
      (is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 8)) (pzl/make-puzzle 8))))))

      (run-tests)


      views.cljs



      (ns npuzzle.views
      (:require
      [re-frame.core :as re-frame]
      [npuzzle.subs :as subs]
      [npuzzle.events :as ev]))

      (defn- on-puzzle-size-changed [e]
      (re-frame/dispatch [::ev/change-puzzle-size (int (-> e .-target .-value))]))

      (defn- on-tile-mouse-down [e]
      (let [idx (.getAttribute (-> e .-target) "data-tileindex")]
      (re-frame/dispatch [::ev/move-tile (int idx)])))

      (defn- tile-div [idx tile]
      [:div :style :text-align :center
      :padding "15px"
      :font-size "20px"
      :border (if (not= :space tile) "1px solid black" :none)
      :background (if (not= :space tile) :lightblue nil)
      :height "25px"
      :width "25px"
      ;;cursor = default for disabling caret on hover over text
      :cursor :default
      :onMouseDown on-tile-mouse-down
      :data-tileindex idx
      (if (= :space tile)
      " "
      tile)])

      (defn- tiles-container [puzzle size tile-fn]
      (into [:div :style :display :inline-grid
      :grid-template-columns (apply str (repeat size "auto "))
      :grid-gap "2px"
      :border "2px solid black"]
      (map-indexed
      (fn [idx tile]
      (tile-fn idx tile)) puzzle)))

      (defn main-panel []
      (let [name (re-frame/subscribe [::subs/name])
      sizes (re-frame/subscribe [::subs/size-choices])
      current-size (re-frame/subscribe [::subs/puzzle-size])
      puzzle (re-frame/subscribe [::subs/puzzle])]
      [:div
      [:h1 "Hello to " @name]
      [:div
      :style :padding "10px"
      (into [:select :name "puzzle-size"
      :on-change on-puzzle-size-changed
      :defaultValue @current-size]
      (for [size @sizes]
      (into [:option :value size size])))]
      (tiles-container @puzzle @current-size tile-div)]))








      share









      $endgroup$




      I'm in the process of creating a n-puzzle solver in Clojurescript. I have the basic model up and running and can move tiles on the screen. I plan to implement A* or such an algorithm to solve a given puzzle. Before I do that, I welcome any general comments for improving the quality of the code right now.



      I am just pasting the most important files only here. The entire repo is here



      puzzle.cljs



       (ns npuzzle.puzzle
      (:require [cljs.test :refer-macros [deftest testing is run-tests]]
      [clojure.zip :as zip]))

      (defn get-tiles [puzzle] (nth puzzle 0))
      (defn get-size [puzzle] (nth puzzle 1))

      (defn set-tiles [puzzle tiles] (assoc puzzle 0 tiles))

      (defn make-puzzle
      ([size]
      [(conj (vec (range 1 (* size size))) :space) size])
      ([tiles size]
      [tiles size]))

      (defn index->row-col [puzzle index]
      (let [size (get-size puzzle)]
      [(quot index size) (mod index size)]))

      (defn row-col->index [puzzle [row col]]
      (let [size (get-size puzzle)]
      (+ (* row size) col)))

      (defn get-tile [puzzle [row col]]
      ((get-tiles puzzle) (+ (* row (get-size puzzle)) col)))

      (defn get-index-of-space [puzzle]
      (.indexOf (get-tiles puzzle) :space))

      (defn get-space-coords [puzzle]
      (index->row-col puzzle (get-index-of-space puzzle)))

      (defn is-space? [puzzle coords]
      (= :space (get-tile puzzle coords)))

      (defn valid-coords? [puzzle [row col]]
      (let [size (get-size puzzle)]
      (and (>= row 0) (>= col 0)
      (< row size) (< col size))))

      (defn get-adjacent-coords [puzzle [row col]]
      (->> '([0 1] [-1 0] [0 -1] [1 0]) ;;'
      (map (fn [[dr dc]]
      [(+ row dr) (+ col dc)]))
      (filter #(valid-coords? puzzle %))))

      (defn inversions [puzzle]
      (let [size (get-size puzzle)
      tiles (get-tiles puzzle)
      inversions-fn
      (fn [remaining-tiles found-tiles inversions]
      (if-let [i (first remaining-tiles)]
      (recur (rest remaining-tiles)
      (conj found-tiles i)
      (+ inversions (- (dec i) (count (filter found-tiles (range i))))))
      inversions))]
      (inversions-fn (remove #:space tiles) # 0)))

      (defn is-solvable? [puzzle]
      (let [inv-cnt (inversions puzzle)
      size (get-size puzzle)
      [row col] (get-space-coords puzzle)]
      (if (odd? size)
      (even? inv-cnt)
      (if (even? (- size row))
      (odd? inv-cnt)
      (even? inv-cnt)))))

      (defn can-move? [puzzle coords]
      ;;Check if any one of the adjacent tiles is the space.
      (->> (get-adjacent-coords puzzle coords)
      (filter #(is-space? puzzle %))
      (first)))

      (defn swap-tiles [puzzle coord1 coord2]
      (let [index1 (row-col->index puzzle coord1)
      index2 (row-col->index puzzle coord2)
      tile1 (get-tile puzzle coord1)
      tile2 (get-tile puzzle coord2)
      tiles (get-tiles puzzle)]
      (set-tiles puzzle
      (-> tiles
      (assoc index1 tile2)
      (assoc index2 tile1)))))

      (defn move [puzzle coords]
      (if (can-move? puzzle coords)
      (swap-tiles puzzle coords (get-space-coords puzzle))
      puzzle))

      (defn random-move [puzzle]
      (let [space-coords (get-space-coords puzzle)
      movable-tiles (get-adjacent-coords puzzle space-coords)
      random-movable-tile (nth movable-tiles (rand-int (count movable-tiles)))]
      (move puzzle random-movable-tile)))

      (defn shuffle-puzzle
      "Shuffles by moving a random steps"
      ([puzzle]
      (let [num-moves (+ 100 (rand 200))]
      (shuffle-puzzle puzzle num-moves)))
      ([puzzle num-moves]
      (if (> num-moves 0)
      (recur (random-move puzzle) (dec num-moves))
      puzzle)))


      puzzle_test.cljs



      (ns npuzzle.puzzle-test
      (:require [cljs.test :refer-macros [deftest testing is run-tests]]
      [npuzzle.puzzle :as pzl]))

      (deftest puzzle-tests
      (let [p1 (pzl/make-puzzle 3)]
      (testing "make-puzzle"
      (is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles p1)))
      (is (= 3 (pzl/get-size p1))))
      (testing "get-tile"
      (is (= 1 (pzl/get-tile p1 [0 0])))
      (is (= 2 (pzl/get-tile p1 [0 1])))
      (is (= 5 (pzl/get-tile p1 [1 1]))))
      (testing "get-index-of-space"
      (is (= 8 (pzl/get-index-of-space p1))))
      (testing "get-space-coords"
      (is (= [2 2] (pzl/get-space-coords p1))))
      (testing "is-space?"
      (is (pzl/is-space? p1 [2 2]))
      (is (not (pzl/is-space? p1 [2 1]))))
      (testing "index->row-col"
      (is (= [1 1] (pzl/index->row-col p1 4)))
      (is (= [2 3] (pzl/index->row-col (pzl/make-puzzle 5) 13))))
      (testing "row-col->index"
      (is (= 4 (pzl/row-col->index p1 [1 1])))
      (is (= 13 (pzl/row-col->index (pzl/make-puzzle 5) [2 3]))))
      (testing "valid-coords?"
      (is (pzl/valid-coords? p1 [1 1]))
      (is (not (pzl/valid-coords? p1 [2 3]))))
      (testing "get-adjacent-coords"
      (is (= #[0 1] [1 0] [1 2] [2 1] (into # (pzl/get-adjacent-coords p1 [1 1]))))
      (is (= #[0 1] [1 0] (into # (pzl/get-adjacent-coords p1 [0 0])))))
      (testing "can-move?"
      (is (pzl/can-move? p1 [1 2]))
      (is (pzl/can-move? p1 [2 1]))
      (is (not (pzl/can-move? p1 [1 1]))))
      (testing "move"
      (is (= [1 2 3 4 5 :space 7 8 6] (pzl/get-tiles (pzl/move p1 [1 2]))))
      (is (= [1 2 3 4 :space 5 7 8 6] (pzl/get-tiles (pzl/move (pzl/move p1 [1 2]) [1 1]))))
      (is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles (pzl/move p1 [0 1])))))
      (testing "inversions"
      (is (= 10 (pzl/inversions (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3))))
      (is (= 41 (pzl/inversions (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4))))
      (is (= 62 (pzl/inversions (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4))))
      (is (= 56 (pzl/inversions (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
      (testing "is-solvable?"
      (is (pzl/is-solvable? (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3)))
      (is (pzl/is-solvable? (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4)))
      (is (pzl/is-solvable? (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4)))
      (is (not (pzl/is-solvable? (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
      (testing "shuffle-puzzle"
      (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 4))))
      (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 6))))
      (is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 9))))
      (is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 3)) (pzl/make-puzzle 3)))
      (is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 8)) (pzl/make-puzzle 8))))))

      (run-tests)


      views.cljs



      (ns npuzzle.views
      (:require
      [re-frame.core :as re-frame]
      [npuzzle.subs :as subs]
      [npuzzle.events :as ev]))

      (defn- on-puzzle-size-changed [e]
      (re-frame/dispatch [::ev/change-puzzle-size (int (-> e .-target .-value))]))

      (defn- on-tile-mouse-down [e]
      (let [idx (.getAttribute (-> e .-target) "data-tileindex")]
      (re-frame/dispatch [::ev/move-tile (int idx)])))

      (defn- tile-div [idx tile]
      [:div :style :text-align :center
      :padding "15px"
      :font-size "20px"
      :border (if (not= :space tile) "1px solid black" :none)
      :background (if (not= :space tile) :lightblue nil)
      :height "25px"
      :width "25px"
      ;;cursor = default for disabling caret on hover over text
      :cursor :default
      :onMouseDown on-tile-mouse-down
      :data-tileindex idx
      (if (= :space tile)
      " "
      tile)])

      (defn- tiles-container [puzzle size tile-fn]
      (into [:div :style :display :inline-grid
      :grid-template-columns (apply str (repeat size "auto "))
      :grid-gap "2px"
      :border "2px solid black"]
      (map-indexed
      (fn [idx tile]
      (tile-fn idx tile)) puzzle)))

      (defn main-panel []
      (let [name (re-frame/subscribe [::subs/name])
      sizes (re-frame/subscribe [::subs/size-choices])
      current-size (re-frame/subscribe [::subs/puzzle-size])
      puzzle (re-frame/subscribe [::subs/puzzle])]
      [:div
      [:h1 "Hello to " @name]
      [:div
      :style :padding "10px"
      (into [:select :name "puzzle-size"
      :on-change on-puzzle-size-changed
      :defaultValue @current-size]
      (for [size @sizes]
      (into [:option :value size size])))]
      (tiles-container @puzzle @current-size tile-div)]))






      clojure clojurescript





      share












      share










      share



      share










      asked 6 mins ago









      nakiyanakiya

      1336




      1336




















          0






          active

          oldest

          votes












          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217110%2fn-puzzle-in-clojurescript%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217110%2fn-puzzle-in-clojurescript%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

          Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar