【问题标题】:Find Duplicate values in a Lua table在 Lua 表中查找重复值
【发布时间】:2020-07-09 20:17:54
【问题描述】:

我有一个自动生成 X 和 Y 值的 Lua 表,我正在尝试使它,如果 X 值与表中的另一个 X 值相同,那么它会做一些事情,现在的事情不是重要的是,我找到的唯一答案是您是否已经知道表格中的内容,例如我不感兴趣的“橙色”“蓝色”。

假设我在表中生成了大量数字,如何检查该表中可能稍后在运行时生成的匹配值。 我的 x、y 值已经四舍五入到小数点后 2 位,即:1.10。 我的 x 和 y 值已经生成到表格中了。

我的代码

在开始时,

positiontableX = {}
positiontableY = {}

在运行时,

newxpos = math.floor (a[1] * 100)/100
newypos = math.floor (a[2] * 100)/100
table.insert (positiontableX, 1, newxpos)
table.insert (positiontableY, 1, newypos)

就表格中生成的数据而言,这是我不需要在此处添加的代码的另一部分。

【问题讨论】:

    标签: lua duplicates


    【解决方案1】:

    这是一个有趣但有点笨拙的解决方案。我在这里假设你不想覆盖任何值:如果你得到一个副本,你想将它添加到表中并继续前进。为了解决这个问题,我将使用'values as keys' solution 立即检查值是否存在(不循环),但使用两个单独的表以免覆盖任何内容。

    local positiontableX = {} --an array where values are stored as values
    local heldposX = {} --an array where values are stored as indexes
    a = {1, 2, 3, 4, 3, 5, 7, 2, 7, 10}
    
    for i = 1, 10 do
      local newxpos = math.floor (a[i] * 100)/100
      if heldposX[newxpos] == nil then  --if this value has never been added yet
        print("new x value " .. newxpos)
        heldposX[newxpos] = true        --add it
      else                              --if this value has been added before
        print("duplicate x value " .. newxpos)
      end
      table.insert (positiontableX, 1, newxpos) --add value to position table
    end
    

    输出

    new x value 1.0
    new x value 2.0
    new x value 3.0
    new x value 4.0
    duplicate x value 3.0
    new x value 5.0
    new x value 7.0
    duplicate x value 2.0
    duplicate x value 7.0
    new x value 10.0
    

    回顾一下,这对每个 x 和 y pos 列表使用两个表。您将为它们中的每一个添加值,但使用一个来确定该值是否已经存在,以便您可以编写一个脚本来做一些特殊的事情(请注意,在我的示例中,我在执行脚本后将值添加到 positiontableX如果它已经存在,但你可以通过移动线条来改变它)。

    【讨论】:

    • 我似乎得到了 ' 新 x 值 -1.98 重复 x 值 -1.98 重复 x 值 -1.98 重复 x 值 -1.98 重复 x 值 -1.98 重复 x 值 -1.98 重复 x 值 -1.98 重复x 值 -1.98 重复 x 值 -1.98'
    • 要么 A)您的算法不断创建重复项,要么 B)您以某种方式循环返回并不断重复单个值。您可以在您评估和插入值的地方发布a 表的一部分或完整的sn-p 代码吗?
    猜你喜欢
    • 2011-02-05
    • 2020-09-10
    • 1970-01-01
    • 2013-05-30
    • 2022-01-22
    • 2019-11-10
    • 2018-09-30
    • 2017-03-16
    相关资源
    最近更新 更多