Skip to content

Commit 306eb82

Browse files
Add solution for valid tic tac toe position
1 parent e4064d8 commit 306eb82

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""Kata url: https://www.codewars.com/kata/68582183cf16719a5ba943df."""
2+
Line = tuple[str, str, str]
3+
Coord = tuple[int, int]
4+
5+
6+
def is_valid_position(board: tuple[Line, Line, Line]) -> bool:
7+
flatten = [cell for line in board for cell in line]
8+
9+
p1 = flatten.count('O')
10+
p2 = flatten.count('X')
11+
if p2 != p1 and (p1 + 1 != p2):
12+
return False
13+
14+
wins = set()
15+
winner = None
16+
17+
for (x, y), (dx, dy) in (
18+
((0, 0), (1, 0)),
19+
((0, 1), (1, 0)),
20+
((0, 2), (1, 0)),
21+
((0, 0), (0, 1)),
22+
((1, 0), (0, 1)),
23+
((2, 0), (0, 1)),
24+
((0, 0), (1, 1)),
25+
((2, 0), (-1, 1)),
26+
):
27+
chks = [(x + i * dx, y + i * dy) for i in range(3)]
28+
29+
for c in "OX":
30+
if all(board[y][x] == c for (x, y) in chks):
31+
wins.update(chks)
32+
winner = c
33+
34+
if len(wins) not in {0,3,5}:
35+
return False
36+
37+
return {
38+
'O': p1 == p2,
39+
'X': p1 != p2,
40+
None: True
41+
}[winner]

0 commit comments

Comments
 (0)