lua-users home
lua-l archive

Re: common prefix?

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


Hello Petite,
Thursday, July 16, 2009, 11:03:17 PM, you wrote:
> Does anyone has a little function to compute the common prefix of a
> list of strings?
str = aList[1] || ''
n = length (str)
for _,s in ipairs(aList) do
 while s:sub(1,n)~=str && n>0 do
 n=n-1
 str=s:sub(1,n)
 end
end
> 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
-- 
Best regards,
 Bulat mailto:Bulat.Ziganshin@gmail.com

AltStyle によって変換されたページ (->オリジナル) /