Skip to content

Instantly share code, notes, and snippets.

@getaaron
Created December 10, 2015 20:13
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 getaaron/8c9620bf777b01674c4b to your computer and use it in GitHub Desktop.
Save getaaron/8c9620bf777b01674c4b to your computer and use it in GitHub Desktop.
// determines the state of a given Connect Four board
// http://www.codewars.com/kata/529962509ce9545c76000afa/train/javascript
function connectFour(board) {
horizontal = straight(board, true);
if (horizontal) return horizontal;
vertical = straight(board, false);
if (vertical) return vertical;
diag = diagonal(board);
if (diag) return diag;
if([].concat.apply([], board).indexOf('-') >= 0) return "in progress"
return "draw";
}
function straight(board, horizontal) {
function row(board, i) { return board[i]; }
function column(board, i) { return board.map(function(value,index) { return value[i]; }); }
row_count = horizontal ? 6 : 7;
col_max = horizontal ? 4 : 3;
for (i = 0; i < row_count; i++) {
this_row = horizontal ? row(board, i) : column(board, i);
for (j = 0; j < col_max; j++) {
var winner = check_slice(this_row.slice(j, j + 4));
if (winner) return winner;
}
}
}
function diagonal(board) {
var winner;
for (i = 0; i < 3; i++) {
for (j = 0; j < 7; j++) {
if (j < 4) {
winner = check_slice([board[i][j], board[i+1][j+1], board[i+2][j+2], board[i+3][j+3]]);
if (winner) return winner;
}
if (j > 2) {
winner = check_slice([board[i][j], board[i+1][j-1], board[i+2][j-2], board[i+3][j-3]]);
if (winner) return winner;
}
}
}
}
function check_slice(slice) {
set = new Set(slice);
if (set.size == 1 && (set.has("R") || set.has("Y"))) {
return Array.from(set)[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment