多维数组,检查不存在的邻居



得到这样的列表:

people[i][j] 

其中ij都从0缩放到n

每个条目看起来都像:

people[1][1] = {genome = 0x000000, immune = 0, healing = 0}

现在我正在遍历这些人,并检查每个邻居,比如:

if people[i][j+1] then ....
if people[i][j-1] then ....
if people[i+1][j] then ....
if people[i-1][j] then ....

但那些站在阵列边界上的人,在一两个方向上没有邻居,这是我的问题。

尝试为字段"?"编制索引(零值)

我知道为什么会出现这个错误,但我现在已经知道如何在我的场景中修复这个问题了。

(顺便说一句:我正在努力解决这个谜题,也许这些信息可以帮助你理解我的场景到期了,我得检查一下邻居。https://codegolf.stackexchange.com/questions/38446/be-an-epidemiologist)

n*4-4个条目只有3个,4个条目只有2个邻居。我可以将它们存储在一个额外的列表中,在其中我可以使用其他检查过程,但我想这将是一个非常糟糕的解决方案。此外,适当的表现也是一个大问题。(假设n为1000,则每次绘制必须进行1000²的4次检查,多次绘制。

有几种方法可以解决这个问题,这里有两种:

if people[i+1] and people[i+1][j] then

if (people[i+1] or {})[j] then

你也可以明确测试你是否在边界上,但这很容易出错:

if j < n and people[i][j+1] then ....
if j > 0 and people[i][j-1] then ....
if i < n and people[i+1][j] then ....
if i > 0 and people[i-1][j] then ....

请注意,您展示的代码实际上只在第一维度(i索引)上有问题,所以只这样做也有效:

if people[i][j+1] then ....
if people[i][j-1] then ....
if i < n and people[i+1][j] then ....
if i > 0 and people[i-1][j] then ....

另一个解决方案是在运行循环之前向people添加两个空数组:

people[-1] = {}
people[n+1] = {}

使用模数运算符。

如果索引从0n - 1,则可以使用:(x + 1) % n(x - 1 + n) % n分别查找下一个和上一个邻居。相反,如果索引是从1而不是0(到n),则将一个1

if people[i][(j + 1) % n] then ....
if people[i][(j - 1 + n) % n] then ....
if people[(i + 1) % n][j] then ....
if people[(i - 1 + n) % n][j] then ....

请注意,限制在这里起着重要作用。

最新更新