Clojure - Iterating through a collection problem
Reading time: 1 minI've been working on my Tic tac toe's board. Starting from the test that I believe will give my the most value, the game-over. As this is the behaviour that will then require testing the win, draw and loss behaviour.
After implementing each row winning combination, I noticed a pattern and refactored the code to make the duplication more apparent, which would allow me to futher refactor to a generalize solution.
[code lang="clojure"]
(defn- top-row [board]
(cells-the-same? board [0 1 2])
)
(defn- middle-row [board]
(cells-the-same? board [3 4 5])
)
(defn- bottom-row [board]
(cells-the-same? board [6 7 8])
)
(defn- left-column [board]
(cells-the-same? board [0 3 6])
)
(defn- middle-column [board]
(cells-the-same? board [1 4 7])
)
[/code]
The code above are very similar, the difference being the input. How could I split this to be more general method which would then operate on the collection.
So I wrote some pseudo code
[code lang="clojure"]
;not working code
(def winning-positions [] [ [0 1 2] [3 4 5] [6 7 8] [0 3 6] [1 4 7]])
(apply (#(cells-the-same? board %) on each item in multi-dimensional array (pass-this-collection-to-the-left winning-positions))
[/code]
I have the basic idea on how I want to approach it, but not sure on the implementation.
I'm hoping tomorrow I will have a better clue on how to implement it in code