两个表作为一个表的区别 [英] Difference between two tables as a table
问题描述
穿着短裤
t1 = {1,3,5,7,9}
t1 = {1,3,5,7,9}
t2 = {1,2,3,4,5,6,7,8,9}
t2 = {1,2,3,4,5,6,7,8,9}
想要的结果:t3 = {2,4,6,8}
result wanted: t3 = {2,4,6,8}
长期解释
我有一个场景中的对象列表,并且有一个不在场景中的所有对象的列表.我试图编写一些简单的代码,使我可以向场景中添加对象,但要确保它不会加载已经加载的对象.
I have a list of objects in a scene, and I have a list of all objects not in the scene. I am trying to write a simple bit of code that will allow me to add objects to the scene but make sure that it does not load an object that has already been loaded.
所以我可以说....
SafeAdd(2,currentOBJlist,notLoadedOBJList)
SafeAdd (2, currentOBJlist, notLoadedOBJList)
并让应用程序从notLoadedOBJList"中加载 2 个随机对象,但所选对象不在currentOBJlist"中
and have the app load in 2 random objects from "notLoadedOBJList" but the chosen object not be in the "currentOBJlist"
推荐答案
未排序的数组
Lua中的表格也是map/dictionary/集合数组/列表.
通过为列表中的每个元素分配 true
来进行设置;这样,您可以通过查找键将其作为一组使用.如果返回的键为 nil
,则该键不存在,否则返回 true
.
Make a set by assigning true
to every element in a list; that way, you get to use it as a set by looking up the key. If the key returned is nil
then it's non-existent, else it'd return 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
设为一个集合.
Notice that we're duplicating objectsInScene
as a set; this should be avoided, if possible i.e. make objectsInScene
a set while originally building it.
如果保证两个列表都可以排序,那么我们比建立一个集合然后查找它要好得多-两遍解决方案,效率不高.
If both lists are guaranteed to be sorted, we can do much better than building a set and then looking it up -- a two-pass solution, not very efficient.
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
这给出了相同的结果,但是没有花费额外的空间或时间;比以前的方法更好.
This gives the same result but without spending extra space or time; it's preferable over the previous method.
这篇关于两个表作为一个表的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!