0

I need a piece of code in lua language that can find sequential items in an array that the number of item in the group exceeds a specific nubmer. Example:if I have the array(the numbers won't be in the right order, randomly distributed)->( 2,5,9,10,11,21,23,15,14,12,22,13,24 ) ; there are two sequential groups (9,10,11,12,13,14,15) and (21,22,23,24 ) . I want the first group to be found if the specific number say (4) or more, or I can get the two groups if the number is (3) or less for example. thanks

0

1 Answer 1

3

The logical way would seem to be to reorder the table and look for gaps in the sequences.

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.