RosettaCodeData/Task/Abbreviations-automatic/Pluto/abbreviations-automatic.pluto
2026-04-30 12:34:36 -04:00

65 lines
2.2 KiB
Text

do -- Abbreviatiions automatic - find the minimum abbreviation lengths for days of the week
-- in various languages
require( "uchar" ) -- RC Pluto Unicode character library
-- returns the table of space delimited words in s
local function getWords( s : string ) : table
local t, cmds, w = s, {}, s
while t:contains( " " ) do
w, t = t:partition( " " )
if w != "" then
cmds[ # cmds + 1 ] = w
end
end
if t != "" then
cmds[ # cmds + 1 ] = t
end
return cmds
end
for dow in io.lines( "daysOfWeekNames.txt" ) do
local names <const> = getWords( dow )
if # names == 0 then
io.write( "\n" )
elseif # names != 7 then
error( dow .. ": expected 7 names" )
elseif # names > 0 then
-- try abbreviation lengths up to the minimum word length
local maxLen, uName = -1, {}
for i, n in ipairs( names ) do
uName[ i ] = uchar.of( n )
local thisLen <const> = uName[ i ]:len()
if thisLen > maxLen then
maxLen = thisLen
end
end
local found = false
for abLen = 1, maxLen do
local prefixes <const> = {}
found = true
for nPos = 1, # names do
local subLen <const> = if uName[ nPos ]:len() < abLen
then uName[ nPos ]:len()
else abLen
end
local ab <const> = uName[ nPos ]:sub( 1, subLen )
if prefixes:contains( ab ) then
found = false
break
else
prefixes[ ab ] = ab
end
end
if found then
io.write( string.format( "%2d %s\n", abLen, dow ) )
break
end
end
if not found then
error( "No unique abbreviations for: " .. dow )
end
end
end
end