如何使用lua查找数组中的顺序项?
我需要一段lua语言的代码,可以在组中的项数超过特定numer的数组中查找顺序项。示例:如果我有数组(数字顺序不正确,随机分布)->(2,5,9,10,11,21,23,15,14,12,22,13,24);有两个连续组(9,10,11,12,13,14,15)和(21,22,23,24)。如果具体数字是(4)或更多,我希望找到第一组,或者如果数字是(3)或更少,我可以得到两组。如何使用lua查找数组中的顺序项?,lua,Lua,我需要一段lua语言的代码,可以在组中的项数超过特定numer的数组中查找顺序项。示例:如果我有数组(数字顺序不正确,随机分布)->(2,5,9,10,11,21,23,15,14,12,22,13,24);有两个连续组(9,10,11,12,13,14,15)和(21,22,23,24)。如果具体数字是(4)或更多,我希望找到第一组,或者如果数字是(3)或更少,我可以得到两组。 谢谢合乎逻辑的方法似乎是对表格重新排序并查找序列中的空白 function table.copy(t) lo
谢谢合乎逻辑的方法似乎是对表格重新排序并查找序列中的空白
function table.copy(t)
local t2 = {}
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
function groups(org, cnt)
-- Returns a table containing tables containing the groups found
local res = {}
local group = {}
tbl = table.copy(org) -- Prevent reordering of Original Table
table.sort(tbl)
local last = nil
for _,val in ipairs(tbl) do
if last and last + 1 ~= val then
if #group >= cnt then
table.insert(res,group)
end
group = {}
end
table.insert(group,val)
last = val
end
if #group >= cnt then
table.insert(res,group)
end
return res
end
local org = { 2,5,9,10,11,21,23,15,14,12,22,13,24 }
local result = groups(org,3)
print('Number of Groups',#result)
合乎逻辑的方法似乎是对表重新排序,并查找序列中的间隙
function table.copy(t)
local t2 = {}
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
function groups(org, cnt)
-- Returns a table containing tables containing the groups found
local res = {}
local group = {}
tbl = table.copy(org) -- Prevent reordering of Original Table
table.sort(tbl)
local last = nil
for _,val in ipairs(tbl) do
if last and last + 1 ~= val then
if #group >= cnt then
table.insert(res,group)
end
group = {}
end
table.insert(group,val)
last = val
end
if #group >= cnt then
table.insert(res,group)
end
return res
end
local org = { 2,5,9,10,11,21,23,15,14,12,22,13,24 }
local result = groups(org,3)
print('Number of Groups',#result)