Skip to content

Instantly share code, notes, and snippets.

@OneCent01
Created January 13, 2018 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OneCent01/6a62e00a3f55a4a9983bfa62c2a3b4ab to your computer and use it in GitHub Desktop.
Save OneCent01/6a62e00a3f55a4a9983bfa62c2a3b4ab to your computer and use it in GitHub Desktop.
var getCurrentRow = function(board, row, col) {
return board[row];
};
var getCurrentCol = function(board, row, col) {
var flatCol = [];
board.forEach(function(row) {
flatCol.push(row[col]);
return row;
});
return flatCol;
};
var getDiagonal = function(board, row, col) {
var flatDiagonal = [];
if(row === col) {
board.forEach(function(rowArr, i) {
flatDiagonal.push(rowArr[i]);
});
} else {
board.forEach(function(rowArr, i) {
flatDiagonal.push(rowArr[rowArr.length - 1- i]);
});
}
return flatDiagonal;
};
var isInDiagonalPath = function(row, col) {
if((row === 0 && (col === 0 || col === 2)) ||
(row === 1 && col === 1) ||
(row === 2 && (col === 0 || col === 2))) {
return true;
} else {
return false;
}
};
var winsWithThisSpace = function(board, row, col, marker=undefined) {
var currentRow = getCurrentRow(board, row, col);
var currentCol = getCurrentCol(board, row, col);
var diagonalArr, minorDiagonalArr;
if(isInDiagonalPath(row, col)) {
diagonalArr = getDiagonal(board, row, col);
if(row === 1 && col === 1) {
minorDiagonalArr = getDiagonal(board, 0, 2);
}
}
var arrayHolder = [currentRow, currentCol, diagonalArr, minorDiagonalArr];
var wins = 0;
var count;
arrayHolder.forEach(function(array) {
count = 0;
if(Array.isArray(array)) {
array.forEach(function(element) {
if(element === '-' || element === marker) {
count++;
}
});
if(count === 3) {
wins++;
}
}
});
return wins;
};
var boardPossibleWins = function(board, marker='X') {
var boardChances = [];
var chanceRow;
board.forEach(function(row, rowIndex) {
chanceRow = [];
row.forEach(function(col, colIndex) {
chanceRow.push(winsWithThisSpace(board, rowIndex, colIndex, marker));
return col;
});
boardChances.push(chanceRow);
return row;
});
return boardChances;
};
var board = [['-','X','-'],
['-','-','O'],
['-','-','X']];
var xChances = boardPossibleWins(board, 'X');
var oChances = boardPossibleWins(board, 'O');
oChances;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment