mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2025-12-19 10:07:46 -05:00
2.7 KiB
2.7 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69373793f5a867f769cde138 | Challenge 153: Tic-Tac-Toe | 29 | 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--
tic_tac_toe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]) should return "X wins".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "X", "X"], ["O", "O", "X"], ["O", "X", "O"]]), "X wins")`)
}})
tic_tac_toe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]]) should return "O wins".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "O", "X"], ["X", "O", "X"], ["O", "O", "X"]]), "O wins")`)
}})
tic_tac_toe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]) should return "Draw".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "O", "X"], ["O", "X", "O"], ["O", "X", "O"]]), "Draw")`)
}})
tic_tac_toe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]) should return "O wins".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "X", "O"], ["X", "O", "X"], ["O", "X", "X"]]), "O wins")`)
}})
tic_tac_toe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]) should return "X wins".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["X", "O", "O"], ["O", "X", "O"], ["O", "X", "X"]]), "X wins")`)
}})
tic_tac_toe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]) should return "Draw".
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(tic_tac_toe([["O", "X", "X"], ["X", "O", "O"], ["X", "O", "X"]]), "Draw")`)
}})
--seed--
--seed-contents--
def tic_tac_toe(board):
return board
--solutions--
def tic_tac_toe(board):
lines = []
for row in board:
lines.append(row)
for c in range(3):
lines.append([board[0][c], board[1][c], board[2][c]])
lines.append([board[0][0], board[1][1], board[2][2]])
lines.append([board[0][2], board[1][1], board[2][0]])
for line in lines:
if all(cell == "X" for cell in line):
return "X wins"
if all(cell == "O" for cell in line):
return "O wins"
return "Draw"