Sort the letters of string in alphabetical order: Difference between revisions

→‎{{header|Lua}}: this seems more like what task had in mind (?)
(→‎{{header|Lua}}: added Lua solution)
(→‎{{header|Lua}}: this seems more like what task had in mind (?))
Line 659:
 
=={{header|Lua}}==
<lang lua>fcoll = {} -- forward collation
Not idiomatic, ASCII assumed..
sl = string.lower -- for case insensitivity
<lang lua>function sorted(s)
for i=0,255 do fcoll[i]=string.char(i) end -- initially just ASCII (for non-letters)
local b, c = {}, ""
s:gsub("(table.)"sort(fcoll, function(ca,b) localreturn sl(a)=string.byte=sl(cb) b[and a]=(<b[a] or 0sl(a)<sl(b)+1 end) -- interleave upper/lower letters
rcoll = {} for i,v in ipairs(fcoll) do rcoll[v]=i end -- reverse collation
for i = 0, 255 do if b[i] then c=c..string.rep(string.char(i),b[i]) end end
 
return c
function sort(s) -- Latin letters lexicographically, uppercase first, anything else by ASCII
local t={} s:gsub("(%S)", function(c) t[#t+1]=c end) -- use "(.)" as pattern to preserve whitespace
table.sort(t, function(a,b) return rcoll[a]<rcoll[b] end)
return table.concat(t)
end
 
print(sortedsort("Now is the time for all good men to come to the aid of their country."))</lang>
{{out}}
<pre>.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy</pre>
<pre> .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Anonymous user