我正在尝试编写一个函数,其中嵌套循环的数量取决于传递给它的整数(numStroke)。例如,当numStrokes为1时,执行的代码应该是:C#递归逻辑
double checkProfitability(GameState state, int numStrokes)
{
double[] possiblePayoffs = new double[50000];
int pPIndex = 0;
double sumOfPayoffs = 0;
double averagePayoff = 0;
for (int i = 0; i <= 5; i++)
{
// Populate possiblePayoffs[]
}
for (int ii = 0; ii < pPIndex; ii++)
{
sumOfPayoffs += possiblePayoffs[i];
}
averagePayoff = sumOfPayoffs/pPIndex;
return averagePayoff;
}
当numStrokes是3时,它应该是:
double checkProfitability(GameState state, int numStrokes)
{
double[] possiblePayoffs = new double[50000];
int pPIndex = 0;
double sumOfPayoffs = 0;
double averagePayoff = 0;
for (int i = 0; i <= 5; i++)
{
state.colors[i]++;
for (int j = 0; j <= 5; j++)
{
state.colors[j]++;
for (int k = 0; k <= 5; k++)
{
// Populate possiblePayoffs[]
}
state.colors[j]--;
}
state.colors[i]--;
}
for (int ii = 0; ii < pPIndex; ii++)
{
sumOfPayoffs += possiblePayoffs[i];
}
averagePayoff = sumOfPayoffs/pPIndex;
return averagePayoff;
}
链接是当numStrokes是6的额外实例中,只是在我想要做的情况下,是不是已经很清楚:
http://hastebin.com/hemolikodo.avrasm
到目前为止,我想出了以下尝试实现numStrokes amou nt嵌套循环,但它不起作用(如果没有其他原因,因为该函数试图在递归调用自身时创建另一个int i副本)。我不确定这个代码是否是正确的方法。我甚至不确定我应该试图递归地做这件事。我认为只是使用巨大的if语句来执行基于numStrokes的值的代码,但更通用的实现似乎更可取。
double checkProfitability(GameState state, int numStrokes, int i)
{
double[] possiblePayoffs = new double[50000];
int pPIndex = 0;
double sumOfPayoffs = 0;
double averagePayoff = 0;
if (numStrokes == 0)
{
// Populate possiblePayoffs[]
}
else
{
for (int i = 0; i <= 5 && numStrokes >= 1; i++)
{
checkProfitability(state, --numStrokes, i);
}
}
for (int ii = 0; ii < pPIndex; ii++)
{
sumOfPayoffs += possiblePayoffs[ii];
}
averagePayoff = sumOfPayoffs/pPIndex;
richTextBox1.Text = averagePayoff.ToString();
return averagePayoff;
}
任何人都可以解释如何正确实施这个吗?
编辑:问题是,我不知道我需要多少嵌套循环,直到运行时。
不应该甚至编译自定义具有相同名称的两个变量。 –
您正在修改'state.colors',但是甚至没有在使用未修改的'pIndex'和'possiblePayoffs'的“return”值中使用它。 – crashmstr
@crashmstr state.colors []用于将值分配给possiblePayoffs。我用注释替换了算法// Populate possiblePayoffs [],因为代码很长。 – user10478