Tic-Tac-Toe

in code


Hackoberfest has made Tic-tac-toe a thing in my life. tictactoe-server opened an issue for a ES6 refactor of the solution checker.

I kicked around the lengthy imperative code check and found I wanted to expand the solution, that I wanted to drop in Tic-tac-toe boards of arbitrary size, and to check them in an efficient manner.

My solution, when given a board and a target character:

  1. Do all the cells of one row contain only the character?
  2. Do all the cells of one column (transposed to a row) contain only the character?
  3. Do all the cells of one diagonal (forward and backwards, transposed to rows) contain only the character?

I transpose the rows because iteration over the columns seems tedious-more code, same end. Rather than write three checks each run once, I fit the code to one check run once.

Check Solution

Let’s dive in!

function check(character, board) {
    return [].concat(board, transpose(board), diagonals(board)).some(row => {
        return row.every(cell => cell === character);
    });
}

Given the board and the target character, use some() to every() check the conditions given above. Does any row have cells containing only the character?

There are two sub-methods called:

Transpose Array

function transpose(array) {
    return array[0].map((_, index) => array.map(row => row[index]));
}

So:

  1. Take the first element, an array.
  2. For each element in that array, map the index of each item in the parent array to that position.

Get Array Diagonals

function diagonals(array) {
    const reversed = array.slice().reverse();

    return [
        array.map((element, index) => array[index][index]),
        array.map((element, index) => reversed[index][index])
    ];
}

To explain:

  1. Walk the multidimensional array in a forward direction to get diagonal element.
  2. Reverse the array and repeat step 1.

Grab it on node and try it today!



A Summer of Running

in running

Achill Half Marathon

in running


Your email address will not be published. Required fields are marked *