堆栈,我无法完全避免这种奇怪的事情。我每次都在评估数组中的位置。每当我收到不同的结果时,通过初始化数组的方式如何?如果有人可以解释一下,我将不胜感激。
在While循环中:正确
0,1,0,1,1,0,0,1
0,1,1,0,0,0,0,0
0,0,0,0,1,1,1,0
0,1,1,0,0,1,0,0
0,0,0,0,0,1,0,0
0,1,1,1,0,1,0,0
0,0,1,0,1,1,0,0
0,0,1,1,0,0,0,0
外部While循环(初始化一次):不正确
0,1,0,1,1,0,0,1
0,1,1,0,0,0,0,0
0,0,1,0,1,0,1,0
0,0,1,1,0,0,1,0
0,0,0,1,0,0,1,0
0,1,1,0,1,1,0,0
0,0,1,1,1,0,1,0
0,0,0,0,1,1,0,0
问题详细信息
连续有8个监狱牢房,每个牢房都被占用或空着。
每天,牢房被占用还是空置都按照以下规则进行更改:
如果一个单元有两个相邻的邻居都被占用或都空着,则该单元将被占用。 否则,它将变为空置。 (请注意,因为监狱是一排,所以该行中的第一个和最后一个单元不能有两个相邻的邻居。)
我们通过以下方式描述监狱的当前状态:如果第i个牢房被占用,则牢房[i] == 1,否则,牢房[i] == 0。
给出监狱的初始状态,在N天后(以及上述N次此类变化)返回监狱状态。
示例1:预期输出
输入:像元= [0,1,0,1,1,0,0,1],N = 7
输出:[0,0,1,1,0,0,0,0]
说明:
下表总结了每天的监狱状况:
第0天:[0,1,0,1,1,0,0,1]
第一天:[0,1,1,0,0,0,0,0]
第二天:[0,0,0,0,1,1,1,0]
第3天:[0,1,1,0,0,1,0,0]
第4天:[0,0,0,0,0,1,0,0]
第5天:[0,1,1,1,0,1,0,0]
第6天:[0,0,1,0,1,1,0,0]
第7天:[0,0,1,1,0,0,0,0]
方法
static public int[] PrisonAfterNDays(int[] cells, int N)
{
int counter = 0;
//Doesn't work if it's here
//int[] temp = new int[8];
while(counter < N)
{
Console.WriteLine(String.Join(",",cells));
//Works if it's here ?!?!?!
int[] temp = new int[8];
for(int j = 1; j < 8-1; j++)
{
if(cells[j-1] == cells[j+1])
{
temp[j] = 1;
}
else
{
temp[j] = 0;
}
}
cells = temp;
counter++;
}
return cells;
}
答案 0 :(得分:2)
请记住,即使int
是值类型,数组也是引用类型,所以int[]
是引用类型。 (请参见What is the difference between a reference type and value type in c#?)
执行cells = temp;
时,您将cells
和temp
指向完全相同的数组!您可以使用以下代码对此进行测试:
int[] a = new int[2];
int[] b = a;
b[0] = 85;
b[1] = 3;
Console.WriteLine(a[0]); // prints 85
Console.WriteLine(a[1]); // prints 3
因此,这意味着在外循环的第二次迭代中,以下代码同时更改了cells[j]
和temp[j]
:
temp[j] = 1;
很明显,这意味着您会得到奇怪的结果。
基于这个原因,我认为您应该在循环中定义temp
。