mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2025-12-19 18:18:27 -05:00
96 lines
2.3 KiB
Markdown
96 lines
2.3 KiB
Markdown
---
|
||
id: 69373793f5a867f769cde138
|
||
title: "Challenge 153: Tic-Tac-Toe"
|
||
challengeType: 28
|
||
dashedName: 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"`.
|
||
|
||
```js
|
||
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"`.
|
||
|
||
```js
|
||
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"`.
|
||
|
||
```js
|
||
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"`.
|
||
|
||
```js
|
||
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"`.
|
||
|
||
```js
|
||
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"`.
|
||
|
||
```js
|
||
assert.equal(ticTacToe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]), "Draw");
|
||
```
|
||
|
||
# --seed--
|
||
|
||
## --seed-contents--
|
||
|
||
```js
|
||
function ticTacToe(board) {
|
||
|
||
return board;
|
||
}
|
||
```
|
||
|
||
# --solutions--
|
||
|
||
```js
|
||
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";
|
||
}
|
||
```
|