【问题标题】:Multidim Array, checking nonexistent neighborsMultidim Array,检查不存在的邻居
【发布时间】:2014-12-14 12:27:56
【问题描述】:

得到一个这样的列表:

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,则 4 次检查每次抽签必须进行 1000² 次,一次又一次抽签。

【问题讨论】:

    标签: arrays list multidimensional-array lua


    【解决方案1】:

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

    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] = {}
    

    【讨论】:

    • 我不明白这个语法:-- {})[j] -- 它是如何工作的?
    • people[i+1] or {} 如果people[i+1]nil,则返回一个空表,因此对其进行索引是有效的。
    【解决方案2】:

    使用取模运算符。

    如果索引是从 0n - 1,您可以使用:(x + 1) % n(x - 1 + n) % n 分别查找下一个和上一个邻居。相反,如果索引来自 1 而不是 0(到 n),则添加 one (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 ....
    

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

    【讨论】:

    • 此解决方案将网格转换为圆环,这意味着例如people[0][3]people[n][3] 现在是邻居。如果这是您想要的,请使用它!否则,请参阅我的答案。
    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多