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

Content added Content deleted
(→‎{{header|Lua}}: added Lua solution)
(→‎{{header|Lua}}: this seems more like what task had in mind (?))
Line 659: Line 659:


=={{header|Lua}}==
=={{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("(.)", function(c) local a=string.byte(c) b[a]=(b[a] or 0)+1 end)
table.sort(fcoll, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) 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
end

print(sorted("Now is the time for all good men to come to the aid of their country."))</lang>
print(sort("Now is the time for all good men to come to the aid of their country."))</lang>
{{out}}
{{out}}
<pre>.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy</pre>
<pre> .Naaccddeeeeeeffghhhiiiillmmmnnooooooooorrrstttttttuwy</pre>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==