2013-03-11 18 views
1

基本上我有一个对象表,每个对象都有一个特定的字段是一个数字。我试图查看是否有任何这些数字条目匹配,我想不出一种办法。我想可能是一个循环的双重循环,一个循环遍历整个表格,另一个循环递减,但是在某些时候不会导致两个值被比较两次?我担心它可能看起来表面上工作,但实际上有微妙的错误。这就是我想象中的代码:试图比较Lua中的一个表的所有条目

for i = #table, 1, -1 do 
    for j = 1, #table do 
     if(table[i].n == table[j].n) then 
      table.insert(table2, table[i]) 
      table.insert(table2, table[j]) 
     end 
    end 
end 

我想插入选定的对象,如表,到另一个预先制作一个没有任何重复。

回答

1

让外层循环遍历整个表,让内层循环始终在外层循环之前启动一个元素 - 这可以避免重复计算和比较对象与自身。另外,如果你打电话给表格,你想检查table这可能会隐藏你想要访问的tableinsert。所以我们说,你打电话给你的输入表t

for i = 1, #t do 
    for j = i+1, #t do 
     if(t[i].n == t[j].n) then 
      table.insert(table2, t[i]) 
      table.insert(table2, t[j]) 
     end 
    end 
end 

不过,如果有三个或多个元素具有相同的值n你将他们中的一些多次添加。你可以使用另一个表来记录哪些元素已经插入:

local done = {} 
for i = 1, #t do 
    for j = i+1, #t do 
     if(t[i].n == t[j].n) then 
      if not done[i] then 
       table.insert(table2, t[i]) 
       done[i] = true 
      end 
      if not done[j] then 
       table.insert(table2, t[j]) 
       done[j] = true 
      end 
     end 
    end 
end 

我承认这是不是真的优雅,但天色已晚在这里,我的大脑拒绝想到整洁的办法。

编辑:事实上...使用另一个表,你可以减少这一个单一的循环。当您遇到新的n时,您将在n处添加一个新值作为辅助表中的关键字 - 值将是您刚刚分析的t[i]。如果您遇到已在表格中的n,则将该已保存的元素和当前的元素添加到您的目标列表中 - 您还可以用true或其他不是表格的东西替换元素:

local temp = {} 
for i = 1, #t do 
    local n = t[i].n 
    if not temp[n] then 
     temp[n] = t[i] 
    else 
     if type(temp[n]) == "table" then 
      table.insert(table2, temp[n]) 
      temp[n] = true 
     end 
     table.insert(table2, t[i]) 
    end   
end 
+0

谢谢!是的,我现在也不担心在这一点上变得优雅。 – user2087398 2013-03-12 00:00:02

+0

@ user2087398无论如何增加了一个不同的解决方案;) – 2013-03-12 00:02:20