public int Neighbours(int xCoordinate, int yCoordinate)
{
xCoordinate -= 1;
yCoordinate -= 1;
int NeighbourCounter = 0;
int incrementer = 0;
int m1 = -1; //istart
int n1 = -1; //jstart
int m2 = 1; //iend
int n2 = 1; //jend
if (xCoordinate == 0)
{
m1 = 1;
}
if (yCoordinate == 0)
{
n1 = -1;
}
if (xCoordinate + 1 == yLen)
{
m2 = 0;
}
if (yCoordinate + 1 == xLen)
{
n2 = 0;
}
for (int xNeighbour = m1; xNeighbour <= m2; xNeighbour++)
{
if (xNeighbour == 0)
{
incrementer = 2;
}
else
{
incrementer = 1;
}
for (int yNeighbour = n1; yNeighbour<n2; yNeighbour += incrementer)
{
if (CurrentGen[yCoordinate + yNeighbour][xCoordinate + xNeighbour] == 1)
{
NeighbourCounter++;
}
}
}
return NeighbourCounter;
}
是否可以提高此代码的效率?这段代码适用于我的Game of Life项目,当我尝试为下一代生命游戏运行此代码时,我似乎遇到了错误。对于我的NextGeneration,我似乎得到了ArrayOutOfBoundsException: -2
。第45行发生此错误。
答案 0 :(得分:0)
请看ArrayIndexOutOfBoundsException
。
抛出以指示已使用非法索引访问数组。索引为负数或大于或等于数组的大小。
if(CurrentGen[yCoordinate + yNeighbour][xCoordinate + xNeighbour] == 1)
您正在访问CurrentGen
。
yCoordinate + yNeighbour
或xCoordinate + xNeighbour
等于-2
。数组从索引0
开始。