Clojure – Iterating through a collection problem

I’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.

(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])
)

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

;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))

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

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s