c# - 递归算法检查 Nim 游戏中是否有可能获胜
问题描述
我找到了以下代码来检查游戏 Nim 是否有可能获胜。评论表明它是由了解他们在做什么的人编写的,但输出似乎是错误的,除非我完全误解了代码的目的。给定特定数量的剩余棋子(值),我想使用递归来确定下一个玩家是否可能获胜n
。谁能解释一下为什么代码不能正常工作?即true
除了 2 种情况外,它都会返回。
using System;
public class Program
{
public static void Main(String[] args)
{
for (int numStix = 1; numStix <= 20; numStix++)
{
bool willWin = nimCalc(numStix);
Console.WriteLine("Number of sticks: " + numStix + " Will win: " + willWin);
}
}
public static bool nimCalc(int n)
{
bool x = false;
//Base cases that guarantees player 1 will lose
if (n == 1 || n == 4)
{
x = false;
}
//Base cases that guarantees player 1 will win
else if (n == 2 || n == 3 || n == 5 || n == 6)
{
x = true;
}
else
{
//If n>6, it calls this recursively to subtract number of sticks to get to winning position
x = nimCalc(n - 2);
//If above method does not guarantee a win, it uses this recursively to obtain win
if (x == false)
{
x = nimCalc(n - 1);
}
}
//Returns boolean
return x;
}
}
解决方案
推荐阅读
- typescript - 在 Yarn 工作区中使用 Typescript 引用时如何添加自定义类型定义?
- python - 如何增加散景中组标签之间的空间
- string - 查找第一个不同的字符串
- json - 有没有一种简单的方法来反序列化 JSON 字符串,将所有数组都保留为字符串?
- php - Inserting slash into CSS
- swift - Get nil when looking for file in subdirectory of main bundle
- javascript - 禁用按钮单击,直到所有输入字段中都有文本(javascript & jquery)
- sql - PostgreSQL - 如何让简单的查询更快
- reactjs - 如何用 React JS 实现 Packery?
- html - 响应式视图,例如使用 Boostrap 4 和 Ember 的 Whatsapp web