【发布时间】:2021-08-26 08:50:27
【问题描述】:
我做了一个算法来检查是哪个玩家赢得了比赛,或者是平局还是比赛还没有结束,但它不适用于某些测试用例。
我不知道我的代码有什么问题。但它不起作用,所以我认为我的算法或代码本身有些问题。
所以我的算法基本上是:
- 将玩家 1 和玩家 2 的动作分开
- 如果是 return 'player1',则检查玩家 1 的走法是否在获胜走法中
- 如果返回'player2',则检查玩家2的走法是否在获胜走法中
- 如果没有获胜者,则检查移动数是否等于 9。如果是,则返回 'tie'
- 否则,如果移动次数小于 9,则返回“不确定”
代码如下:
def match(a1,a2):
a1.sort()
for solution in a2:
if a1 == solution:
return True
return False
def ticTacToeWinner(moves, n):
# --- Variables ---
p1 = []
p2 = []
winning_moves = [
[[0,0],[0,1],[0,2]],
[[1,0],[1,1],[1,2]],
[[2,0],[2,1],[2,2]],
[[0,0],[1,0],[2,0]],
[[0,1],[1,1],[2,1]],
[[1,0],[2,1],[3,1]],
[[0,0],[1,1],[2,2]],
[[0,2],[1,1],[2,0]],
]
winner = None
# --- Loops ---
for i in range(1,n+1): # separate the moves for each player
if i % 2 == 0:
p2.append(moves[i-1])
else:
p1.append(moves[i-1])
# --- Conditionals ---
if len(p1) >= 3: # check if the player1 has more than 3 moves
if match(p1,winning_moves) == True: # check if the moves of player1 is in the winning moves
winner = 'player1' # winner is player 1
return winner
if len(p2) >= 3: # check if the player2 has more than 3 moves
if match(p2,winning_moves) == True: # check if the moves of player 2 is in the winning moves
winner = 'player2' # winner is player 2
return winner
if not winner: # there are no winners
if n == 9: # board is full so it's draw
return 'draw'
elif n < 9: # board is not full
return 'uncertain'
这段代码是我对这个问题的解决方案: https://www.codingninjas.com/codestudio/problems/tic-tac-toe-winner_1214545?topList=top-apple-coding-interview-questions
该代码仅适用于那里的 2 个测试用例,其他所有测试用例都不正确
输入输出示例:
ticTacToeWinner([[0,0],[2,2],[0,1],[1,1],[0,2]],5) -> 'player1'
因为玩家 1 的走法是:[[0,0],[0,1],[0,2]],这在棋盘顶部形成了三个 X
顶部的匹配功能是检查玩家的动作是否在获胜动作表中。
这里是不能使用代码的测试用例之一:
5
9
2 0
0 1
1 1
1 0
1 2
0 0
2 1
2 2
0 2
4
1 2
1 0
2 0
1 1
1
2 0
9
2 0
1 2
0 1
0 0
0 2
2 1
2 2
1 1
1 0
3
0 2
2 0
0 0
【问题讨论】:
-
这是该算法的面试问题链接:codingninjas.com/codestudio/problems/…
-
请准确说明代码出错的地方
-
你的代码对于不知道它的人来说很难阅读,因为我们不知道变量是什么样的。请至少在函数定义上方的 cmets 中给出
a1, a2和moves, n的示例值。 -
另外请指定不起作用的测试用例,输出是什么,以及您期望它是什么。
-
该网站需要一个帐户,而一个帐户需要从一组封闭的大学中进行选择,所以我不会创建一个帐户。我们需要这里的所有信息来重现问题。
标签: python algorithm tic-tac-toe