lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

Does anyone has a little function to compute the common prefix of a list of strings?

E.g.:

local aList = { 'foobarbaz', 'foobar', 'foo' }

print( CommonPrefix( aList ) )

> foo

TIA.

Cheers,

PA.

P.S.

FWIW, this is what I have concocted so far, but it looks, hmmm, not right :)

function LCP()
    local aPrefix = nil

    return function( aValue )
        local aValue = tostring( aValue ) or ''
              aPrefix = aPrefix or aValue
        local aLength = math.min( aPrefix:len(), aValue:len() )

        for anIndex = 0, aLength do
            aPrefix = aPrefix:sub( 1, aLength - anIndex )

            if aValue:find( aPrefix, 1, true ) then
                break
            end
        end

        return aPrefix
    end
end


local aList = { 'foobarbaz', 'foobar', 'foo' }
local aLCP = LCP()

for anIndex, aValue in ipairs( aList ) do
    print( anIndex, aLCP( aValue ) )
end