Sort the letters of string in alphabetical order: Difference between revisions
Sort the letters of string in alphabetical order (view source)
Revision as of 15:50, 28 August 2022
, 1 year agosyntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 16:
=={{header|11l}}==
<
DefaultDict[Char, Int] d
L(c) s
Line 26:
print(sorted_str(‘The quick brown fox jumps over the lazy dog, apparently’))
print(sorted_str(‘Is this misspelling of alphabetical as alphabitical a joke ?’))</
{{out}}
Line 36:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
PROC Test(CHAR ARRAY s)
Line 48:
Test("The quick brown fox jumps over the lazy dog, apparently")
Test("Now is the time for all good men to come to the aid of their country.")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_the_letters_of_string_in_alphabetical_order.png Screenshot from Atari 8-bit computer]
Line 66:
=={{header|Ada}}==
<
with Ada.Containers.Generic_Array_Sort;
Line 85:
begin
Put_Line (B); Sort (B); Put_Line (B);
end Sort_Letters;</
{{out}}
<pre>When Roman engineers built a bridge, they had to stand under it while the first legion marched across. If programmers today worked under similar ground rules, they might well find themselves getting much more interested in Ada!
Line 92:
=={{header|ALGOL 68}}==
As with the Wren, Go and probably other samples, this defines a bubble sort to sort the text. Non-alphabetic characters are retained.
<
# returns s with the characters sorted into lexicographic order #
OP LSORT = ( STRING s )STRING:
Line 114:
print( ( LSORT "The quick brown fox jumps over the lazy dog, apparently", newline ) )
print( ( LSORT "Now is the time for all good men to come to the aid of their country.", newline ) )
END</
{{out}}
<pre>
Line 123:
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang
{{out}}
<pre> sort 'Now is the time for all good men to come to the aid of their country.'
Line 129:
=={{header|AutoHotkey}}==
<
oChar := []
for i, v in StrSplit(str)
Line 141:
result .= letter
return result
}</
Examples:<
str2 := "Now is the time for all good men to come to the aid of their country."
MsgBox, 262144, , % result := str1 " ->`n" sortLetters(str1)
. "`n`n" str2 " ->`n" sortLetters(str2, 0)</
{{out}}
<pre>The quick brown fox jumps over the lazy dog, apparently ->
Line 155:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax GAWK -f SORT_THE_LETTERS_OF_STRING_IN_ALPHABETICAL_ORDER.AWK
BEGIN {
Line 172:
return(str)
}
</syntaxhighlight>
{{out}}
<pre>
Line 180:
=={{header|BCPL}}==
<
let sortchars(str) be
Line 200:
sortchars(string)
writef("%S*N", string)
$)</
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
Line 206:
=={{header|C}}==
<
/* Sort a character string in place */
Line 224:
puts(s);
return 0;
}</
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
Line 230:
=={{header|C++}}==
<
#include <iostream>
Line 241:
std::cout << s << std::endl;
return 0;
}</
{{out}}
<pre>Now is the time for all good men to come to the aid of our country.
Line 248:
=={{header|C#|CSharp}}==
Dubbing the following sorting method as "Slacksort". This "Slacksort" method can easily be adapted for reverse sorting, or removing other characters besides space. Not recommended for larger strings though.
<
class Program {
static void Main(string[] args) {
Line 263:
Write( nl + "done..." );
}
}</
Note: this is a bit of a tribute to the original task description and initial Ring entry, so the typographical errors have intentionally not been corrected.
{{out}}
Line 275:
=={{header|CLU}}==
<
% that "every implementation must provide at least 128,
% but no more than 512, characters".
Line 303:
stream$putl(po, str)
stream$putl(po, sort_string(str))
end start_up</
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
Line 309:
=={{header|Comal}}==
<
0020 DIM count#(0:255)
0030 FOR i#:=1 TO LEN(s$) DO count#(ORD(s$(i#))):+1
Line 326:
0160 strsort(test$)
0170 PRINT test$
0180 END</
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
Line 332:
=={{header|Common Lisp}}==
<
(sort "Now is the time for all good men to come to the aid of their country." #'char<=)
</syntaxhighlight>
{{out}}
<pre>
Line 341:
=={{header|Draco}}==
<
proc nonrec stringsort(*char str) void:
[256] word counts;
Line 376:
stringsort(s);
writeln(s)
corp</
{{out}}
<pre>Now is the time for all good men to come to the aid of their country.
Line 385:
[https://github.com/ljr1981/rosettacode_answers/blob/main/src/sort_string_letters/sort_string_letters.e Example Code]
<
class
SORT_STRING_LETTERS
Line 424:
end
</syntaxhighlight>
Notice the use of Design-by-Contract in the "ensure" at the end of `sort_string'. At testing runtime, we want the routine itself to ensure that the resulting string has no space character and that every character that we passed in the `s' argument is represented in the result string. We even go so far as to ensure that repeating characters are all represented. We could go further, but we felt these contracts
Line 435:
[https://github.com/ljr1981/rosettacode_answers/blob/main/testing/rc_sort_string_letters/rc_sort_string_letters_test_set.e Test Code]
<
class
RC_SORT_STRING_LETTERS_TEST_SET
Line 468:
end
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
// Alphabetic sort. Nigel Galloway: July 27th., 2021
let fG n g=let g=g|>Seq.countBy id|>Map.ofSeq in [for n in n->if Map.containsKey n g then [|for g in 1..g.[n]->n|]|>System.String else ""]|>String.concat ""
Line 480:
n.WriteLine(Turkish (String.filter((<>)' ') "Meseleyi anlamağa başladı"))
</syntaxhighlight>
{{out}}
<pre>
Line 488:
=={{header|FreeBASIC}}==
<
function value( s as string ) as integer
'maps a=A=0, b=B=1, etc
Line 513:
sortstr( example, sorted )
print sorted</
{{out}}<pre>aaaaaaaaaabbccddddddddeeeeeeeeefgggghiiIiiiiklmmmnnnnnnnnnOooooopprrrrrrrstttuuuvwwyyyy</pre>
=={{header|Go}}==
As in the case of the Wren entry, we write a function to bubble sort the characters of a string since this method is not, of course, used in Go's standard 'sort' package.
<
import (
Line 561:
fmt.Printf("Sorted ->%s\n\n", res)
}
}</
{{out}}
Line 573:
=={{header|Haskell}}==
<
main :: IO ()
Line 579:
print $
sort
"Is this misspelling of alphabetical as alphabitical a joke ?"</
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
Line 585:
Or, sketching a rough re-phrase of the question:
<
main :: IO ()
Line 597:
qSort (x : xs) = qSort below <> (x : qSort above)
where
(below, above) = partition (<= x) xs</
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
Line 604:
Or, just constructing a sorted string from the character counts:
<
----------------- MAP OF CHARACTER COUNTS ----------------
Line 621:
. charCounts
)
"Was the misspelling of alphabetical as alphabitical a joke ?"</
{{Out}}
<pre>" ?Waaaaaaaaabbcceeeefghhhiiiiijkllllllmnoopppssssttt"</pre>
=={{header|J}}==
J's builtin is 'grade' and sort is a derived function whose domain includes sequences of characters, so:<
text1=: 'The sentence "The quick brown fox jumps over the lazy dog" uses every letter in the alphabet.'
/:~ text0
Taehiissstt
/:~ text1
"".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz</
However, sorting characters is easy to implement using [[wp:Bucket_sort|bucket sort]]:<
Taehiissstt
{{a.#~<:#/.~a.,y}} text1
"".TTaaabbccdeeeeeeeeeeeeeefghhhhhiijklllmnnnnooooppqrrrrssssttttttuuuvvwxyyz</
(Since there's no comparison between pairs in bucket sort, performance here is O(n) rather than O(n log n).)
Line 645:
An efficient way to sort an arbitrary JSON string is to use the code points of the constituent characters:
<syntaxhighlight lang="jq">
def sort_by_codepoints:
explode | sort | implode;</
For example:
<
| sort_by_codepoints</
<syntaxhighlight lang="text">def sort_by_characters:
explode | map([.]|implode) | sort | add;</
"✁✂✃✄✆✇✈✉✌✍✎✏✐✑✒✓✔✕✖✗✘✙✚✛✜✝✞✟✠✡✢✣✤✥✦✧✩✪✫✬✭✮✯✰✱✲✳✴✵✶✷✸✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋❍❏❐❑❒❖❘❙❚❛❜❝❞❡❢❣❤❥❦❧❶❷❸❹❺❻❼❽❾❿➀➁➂➃➄➅➆➇➈➉➊➋➌➍➎➏➐➑➒➓➔➘➙➚➛➜➝";
Line 660:
dingbats
| (sort_by_codepoints==sort_by_characters)
</
<pre>
true
Line 668:
=={{header|Julia}}==
<
high <= low && return array
middle = low + div(high - low, 2)
Line 712:
testmergesort("forever julia programming language")
testmergesort("Now is the time for all good men to come to the aid of their country.", false)
</
<pre>
Unsorted -> forever julia programming language
Line 721:
=== case insensitive quicksort ===
<
length(array) < 2 && return array
mid, left, right = first(array), eltype(array)[], eltype(array)[]
Line 739:
testqsort("forever julia programming language")
testqsort("Now is the time for all good men to come to the aid of their country.")
</
<pre>
Unsorted -> forever julia programming language
Line 748:
=== alphabet-only counting version ===
<
const alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
Line 760:
println(lettercountingsort("Now is the time for all good men to come to the aid of their country."))
</
<pre>
aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy
Line 766:
=={{header|Lua}}==
<
sl = string.lower -- for case insensitivity
for i=0,255 do fcoll[i]=string.char(i) end -- initially just ASCII (for non-letters)
Line 778:
end
print(sort("Now is the time for all good men to come to the aid of their country."))</
{{out}}
<pre>.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy</pre>
Concise version, implicit rather than explicit collation sequence table, adequate for this use, same output:
<
local sl,t=string.lower,{} s:gsub("(%S)", function(c) t[#t+1]=c end) -- use "(.)" as pattern to preserve whitespace
table.sort(t, function(a,b) return sl(a)==sl(b) and a<b or sl(a)<sl(b) end) -- implicitly
Line 788:
end
print(sort("Now is the time for all good men to come to the aid of their country."))</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
sortstring["Now is the time for all good men to come to the aid of their country."]</
{{out}}
<pre>". aaccddeeeeeeffghhhiiiillmmmnnNooooooooorrrstttttttuwy"</pre>
=={{header|Nim}}==
<
func sorted(text: string; omitSpaces = false): string =
Line 806:
echo sorted("The quick brown fox jumps over the lazy dog, apparently", false)
echo sorted("Now is the time for all good men to come to the aid of their country.", true)</
{{out}}
Line 818:
However, uppercase and lowercase letters may be separate (like in ASCII), fully or partially interspersed.
The output of this program may differ in that regard.
<
type
Line 867:
writeLn(alphabeticallySorted(s))
end
end.</
=={{header|Perl}}==
<
use strict; # https://rosettacode.org/wiki/Sort_the_letters_of_string_in_alphabitical_order
Line 906:
1 while s/(.)(.)(??{$1 le $2 && '(*FAIL)'})/$2$1/g;
return $_;
}</
{{out}}
<pre>
Line 933:
=={{header|Phix}}==
Not sure this algorithm actually ''has'' a name, but it certainly ain't the fastest, though it possibly ''is'' just about the shortest...<br><small>(If pressed I would dub this "Unoptimised bubble sort without the swapped flag")</small>
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 950:
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Original:\"%s\",\n Sorted:\"%s\"\n Builtin:\"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)})</span>
<!--</
{{out}}
<pre>
Line 959:
===case insensitive===
You can make this case insensitive by applying lower() on each internal comparison, whereas with the builtins that is done (more efficiently) by extracting a custom tagsort.<br><small>(Just to keep you on your toes I've also replaced the algorithm with a fractionaly saner insertion sort, and just to be awkward I've added the baNAnaBAnaNA case.)</small>
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">string_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 979:
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Now is the time for all good men to come to the aid of their country."</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"baNAnaBAnaNA"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (just to be awkward)</span>
<!--</
{{out}}
<pre>
Line 990:
</pre>
Should you want/prefer the output of baNAnaBAnaNA to be AAAaaaBaNNnn, change the test (leaving the builtin/cia as an exercise) to
<!--<
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">32</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<!--</
Or of course for aaaAAAbBnnNN use
<!--<
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">or</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;">-</span><span style="color: #000000;">32</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
<!--</
=={{header|Python}}==
<
from functools import reduce
Line 1,055:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>" ?Iaaaaaaaabbcceeefghhhiiiiiijkllllllmnoopppsssssttt"</pre>
Line 1,061:
=={{header|Raku}}==
===Semi-realistic version===
<syntaxhighlight lang="raku"
constant @lexographic_order = sort *.fc, map &chr, 1..255;
Line 1,074:
Now is the time for all good men to come to the aid of their country.
END
</syntaxhighlight>
{{out}}
<pre>
Line 1,089:
Sorted output is wrapped in double guillemots to make it easier to see where it starts and ends.
<syntaxhighlight lang="raku"
my $chars = $string.chars;
loop {
Line 1,116:
say "\nExtended test string:\n" ~ my $test = (32..126)».chr.pick(*).join;
say wrap moronic-sort $test;</
{{out}}
Line 1,136:
The particular string used is from a typing drill devised by Charles E. Weller in the early 20th century.
<
parse arg y /*generate the array elements (items).*/
if y='' then y= "Now is the time for all good men to come to the aid of their country."
Line 1,154:
/*──────────────────────────────────────────────────────────────────────────────────────*/
make@: parse arg z; #= length(z); do j=1 for #; @.j= substr(z, j, 1); end; return
makeS: parse arg a; $=; do j=1 for #; $= $ || @.j; end; return</
{{out|output|text= when using the default input:}}
<pre>
Line 1,162:
=={{header|Ring}}==
<
see "working..." + nl
see "Sort the letters of string in alphabitical order:" + nl
Line 1,181:
see "Output: " + str + nl
see "done..." + nl
</syntaxhighlight>
{{out}}
<pre>
Line 1,193:
=={{header|VBScript}}==
VBScript can't index a string so first we convert the string to an array of chars, then use join to get back a string
<syntaxhighlight lang="vb">
sub bubble(arr)
n = UBound(arr)
Line 1,217:
s1=join(a,"")
wscript.echo s1
</syntaxhighlight>
{{out}}
<pre>
Line 1,224:
=={{header|Wren}}==
Well, we'll write a function for a bubble sort which we don't have in Wren-sort because it's normally much slower than the other methods. However, it's fast enough here.
<
var chars = s.toList
var n = chars.count
Line 1,249:
System.print(["Unsorted->" + str[0], "Sorted ->" + bubbleSort.call(str[0], str[1])].join("\n"))
System.print()
}</
{{out}}
Line 1,261:
=={{header|XPL0}}==
<
func StrLen(Str); \Return number of characters in an ASCIIZ string
Line 1,283:
Text(0, Sort("Pack my box with five dozen liquor jugs."));
CrLf(0);
]</
{{out}}
Line 1,293:
=={{header|Yabasic}}==
<
// by Galileo, 04/2022
Line 1,320:
print text$
print Sorted$(text$)</
{{out}}
<pre>Sort the letters of string in alphabitical order.
|