Actually, for your expected solution I wouldn't use an array at all.
To see whether a series of pins on a game board (e.g. Tic-Tac-Toe or Connect Four) is either horizontally, vertically or diagonally connected, just use simple algebra:
In your mind, translate the board in a way that you put each row next to the previous row, e.g.:
| 0 | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 | => | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ...
...
You will notice that the board's positions will simply become plain indices.
In this example, index 1
and index 5
are vertically connected, because the board's width is 4
. So, the distance between vertically connected pins always is the board's width (i.e. if the board's width is 4
, then 1
+ 4
= 5
).
So, your functions to determine whether pins are vertically, horizontally or diagonally connected could be as simple als this (I used very simple and verbose implementations here for demonstration purposes. If your mathematical knowledge is higher, feel free to optimize*):
const _boardWidth = 4;
function isHorizontallyConnected(indexA, indexB)
{
const rowA = Math.Floor(indexA / _boardWidth);
const rowB = Math.Floor(indexB / _boardWidth);
if (rowA === rowB && Math.Abs(indexB - indexA) === 1) return true;
return false;
}
function isVerticallyConnected(indexA, indexB)
{
const rowA = Math.Floor(indexA / _boardWidth);
const rowB = Math.Floor(indexB / _boardWidth);
const columnA = indexA % _boardWidth;
const columnB = indexB % _boardWidth;
if (columnA === columnB && Math.Abs(rowB - rowA) === 1) return true;
return false;
}
function isDiagonallyConnected(indexA, indexB)
{
...
}
I left the implementation of the isDiagonallyConnected
function for you to experiment.
*An optimized version of the isVerticallyConnected
function, for instance, could simply be: return Math.Abs(indexB - indexA) === _boardWidth;