mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2025-12-19 10:07:46 -05:00
2.3 KiB
2.3 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69373793f5a867f769cde138 | Challenge 153: Tic-Tac-Toe | 28 | challenge-153 |
--description--
Given a 3×3 matrix (an array of arrays) representing a completed Tic-Tac-Toe game, determine the winner.
- Each element in the given matrix is either an
"X"or"O".
A player wins if they have three of their characters in a row - horizontally, vertically, or diagonally.
Return:
"X wins"if player X has three in a row."O wins"if player O has three in a row."Draw"if no player has three in a row.
--hints--
ticTacToe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]) should return "X wins".
assert.equal(ticTacToe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]), "X wins");
ticTacToe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]]) should return "O wins".
assert.equal(ticTacToe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]]), "O wins");
ticTacToe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]) should return "Draw".
assert.equal(ticTacToe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]), "Draw");
ticTacToe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]) should return "O wins".
assert.equal(ticTacToe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]), "O wins");
ticTacToe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]) should return "X wins".
assert.equal(ticTacToe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]), "X wins");
ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]) should return "Draw".
assert.equal(ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]), "Draw");
--seed--
--seed-contents--
function ticTacToe(board) {
return board;
}
--solutions--
function ticTacToe(board) {
const lines = [];
for (let row of board) {
lines.push(row);
}
for (let c = 0; c < 3; c++) {
lines.push([board[0][c], board[1][c], board[2][c]]);
}
lines.push([board[0][0], board[1][1], board[2][2]]);
lines.push([board[0][2], board[1][1], board[2][0]]);
for (let line of lines) {
if (line.every(cell => cell === "X")) return "X wins";
if (line.every(cell => cell === "O")) return "O wins";
}
return "Draw";
}