lua-users home
lua-l archive

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


Petite Abeille <petite.abeille <at> gmail.com> writes:

> 
> 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.
> 

I think this is really a matching problem

------------------------ start
function getPrefix(t)
    -- empty tables should returned an empty string
    local prefix = ""
    for k,v in pairs(t)  do    
        if #prefix == 0 then
            -- first entry in the table is the longest prefix
            prefix = v
        else
            repeat 
                -- if the prefix matches this is still the longest prefix
                if string.match(v, '^'..prefix) then break end
                -- remove the last character in the prefix
                prefix = string.sub(prefix,1,#prefix-1)
            until #prefix == 0
        end
        -- we much check for an empty prefix otherwise we would 
        -- use the next string as the prefix
        if #prefix == 0 then break end
    end 
    return prefix
end

assert ('foo' == getPrefix({'foobarbaz', 'foobar', 'foofoo'}))
---------------------------end
For efficiency you could set the prefix to "^" so you would not have to 
concatenate the caret in each loop. But this is easier to code.

Andre