Click Here To Fix My Bugs

05 August 2021

In this blog post I will present a bug I introduced to a Noughts and Crosses (Tic Tac Toe, for the Yanks) game. How soon can you spot the problem?

Here's the bug report, sent via the WhatsApp family group chat...

Oh no! The book emoji won despite only having two pieces in a row. Have a think about how you might represent the game state, and how you might implement the code to find a winning piece. Are any of your bug-squashing senses tingling yet?

Here’s the dodgy code I wrote at first. Can you spot the bug? (n.b. any falsy items are considered as non-consecutive, that’s intentional!)

The function accepts an array, representing a row, column or diagonal of game state, and a target number of consecutive items for which to search.

The function should find the first instance of targetNumberOfConsectiveItems items in a row in an array, and return the item having the consecutive run. Examples:

targetNumberOf ConsectiveItems array Should Return
3 ["X", "X", "X"] "X"
3 ["X", "X", "O"] null
4 ["X", "O", "O", "O", "O"] "O"

Try to fix the bug yourself, or use the hints below for a helping hand to the solution.


Select a hint...

So did you manage to find the bug and fix it? Here’s the explanation with the fixed version of the function.

The function steps through the array (which is the internal representation of the game state, in this case).

Items in the array are compared pairwise, with a count of consecutive pairs kept in the numberOfConsecutiveFound variable. When the target number of consecutive items is found the last item found is returned, as demonstrated by the three "X’s" in a row below:

Unfortunately, I had forgotten to reset the numberOfConsecutiveFound after discovering a pair of non-consecutive items.

Example in the buggy version ["X", "X", "O", "O"] is counted as a run of three:

The numberOfConsecutiveFound should be reset after a run is broken:

And finally here’s the fix code - line 13 saves the day. Well done if you already figured it out!