Sunday, December 22, 2019

Golfing Tic-Tac-Toe in Javascript


Recently while searching for something completely unrelated to codegolfing, I came across a thread on stackoverflow which piqued my interest: https://stackoverflow.com/questions/2245801/code-golf-tic-tac-toe.

For those unfamiliar with the term, code golfing is essentially the art of implementing a certain program or algorithm in the least amount of code possible – a fun way to exercise your competitive and creative coding prowess. On a more practical front, it can also be a good way to practice writing efficient code which translates over to more serious coding endeavors.

The challenge was simple: Write a function which accepts an integer array of 9 integers (0 representing blank cell on the board, and 1 and 2 representing the X and O players, respectively) and output one of the following integer values:

·         0 if the board is empty or there is no winner
·         1 if player ‘X’ has won
·         2 if player ‘O’ has won

Scrolling down I found a 114 character Javascript implementation. I already knew what code golfing was, but I hadn’t really done it in a competitive context before.  I had to of course try my hand at beating out the JS implementation.

After thinking about it for a few minutes I whipped up the following solution:







The code is fairly straightforward – we’re decrementing the variable i and for each iteration we’re setting r to the value of bitwise AND’ing the 3 respective positions of a “win” board state. So for instance, at the start i will be 8, and r will be set to r=b[2]&b[4]&b[6]  - which is the diagonal winning combo spanning from the top right corner of our board to the bottom left corner. Remember – in JS multiplying a numerical char string by 1 will cast as an integer value.

The code takes advantage of the following truths: 
Any combos of  the Xs/Os AND 0 will be 0
1 AND 2 will be 0
1 AND 1 will be 1
2 AND 2 will be 2

Here's the gist of it: the only time when r will set to a non-zero value is when each of the three board elements we AND together are all non-zero and the same value, aka either all 1s (aka all ‘X’s) or all 2s (aka all ‘O’s). When r is set to a non-zero value then the evaluation of the !r within the while loop will be false and thus break the loop. Otherwise, r will be set to zero, !r will evaluate to true, and the loop will go on.

So in the end my version was 7 bytes shorter than the JS implementation I had found on stackoverflow. I have a feeling that utilizing some other JS constructs could knock the footprint on that by at least another ~20-30 lines of code. Perhaps someone will incorporate this into a full-fledged golfed tic-tac-toe game.

If you have your own version you’d like to share please feel free to include it in a comment below!