简写为
t1 = {1,3,5,7,9} t2 = {1,2,3,4,5,6,7,8,9} 需要的结果: t3 = {2,4,6,8}
长解释
我有一个场景中的对象列表,还有一个没有在场景中的所有对象的列表。我正在尝试编写一段简单的代码,允许我将对象添加到场景中,但确保它不会加载已经加载的对象。
这样我就可以说.
SafeAdd (2,currentOBJlist,notLoadedOBJList)
将应用程序从"notLoadedOBJList“中加载到两个随机对象中,但所选对象不在"currentOBJlist”中。
发布于 2019-08-07 06:33:30
未排序数组
Lua中的表除了是一个数组/列表之外,也是一个映射/字典/设置。
通过向列表中的每个元素分配true
来创建一个集合;这样,您就可以通过查找键将其作为一个集合使用。如果返回的密钥是nil
,那么它就不存在,否则它将返回true
。
function notInScene(allObjects, objectsInScene)
-- build a set out of objectsInScene
-- this step can be avoided, if it's already a set
local set = {}
for _, v in ipairs(objectsInScene) do
set[v] = true
end
-- populate output
local notPresent = { }
for _, v in ipairs(allObjects) do
if (set[v] == nil) then
table.insert(notPresent, v)
end
end
return notPresent
end
local t1 = {1,3,5,7,9}
local t2 = {1,2,3,4,5,6,7,8,9}
local t3 = notPresent(t2, t1)
for _, v in ipairs(t3) do print(v) end
输出
2
4
6
8
请注意,我们将objectsInScene
复制为一个集合;应该避免这种情况,如果可能的话,即在最初构建objectsInScene
时将其设置为一个集合。
排序数组
如果这两个列表都被保证排序,我们可以做得更好,比建立一个集合,然后查找它--一个两次通过的解决方案,效率不高。
function notInScene(allObjects, objectsInScene)
j = 1
local notPresent = {}
for i = 1, #allObjects do
if (allObjects[i] == objectsInScene[j]) then
j = j + 1
elseif (allObjects[i] < objectsInScene[j]) then
table.insert(notPresent, allObjects[i])
end
i = i + 1
end
return notPresent
end
这给出了同样的结果,但不需要花费额外的空间或时间;它比以前的方法更好。
https://stackoverflow.com/questions/57388045
复制相似问题