13
\$\begingroup\$

Write a program that takes a string and outputs all the characters in alphabetical order. Spaces and symbols can be ignored or deleted, but the upper- and lowercase letters must remain the same case.

Sample input:

Johnny walked the dog to the park.

Sample output

aaddeeeghhhJklnnoooprtttwy

Rules:

• Any language

• Shortest code wins.

\$\endgroup\$
  • 5
    \$\begingroup\$ How to sort upper/lower case letters? Upper before lower, vice versa or stable with the input? \$\endgroup\$ – Howard Jan 22 '14 at 8:51
  • \$\begingroup\$ Does it need to handle any letters outside of the basic Latin alphabet ("English alphabet")? \$\endgroup\$ – Sebastian Negraszus Jan 22 '14 at 11:02
  • 3
    \$\begingroup\$ From the title, I was hoping I could get away with displaying "Sentence in Alphabetical Order". Or "ceeennst". (OK, "Sceeennt", if you insist on correct capitalization and ASCII order.) \$\endgroup\$ – keshlam Jan 22 '14 at 16:16
  • \$\begingroup\$ When you Spaces and symbols can be ignored or deleted, does that mean must be ignored; or is output such as , .aaddeeeff allowed? \$\endgroup\$ – blutorange May 20 '15 at 18:34
  • 2
    \$\begingroup\$ Should there not be 2 ks in the output? \$\endgroup\$ – HyperNeutrino Apr 27 '17 at 3:41

23 Answers 23

2
\$\begingroup\$

MathGolf, 2 bytes

áδ

Try it online!

Example output

      .aaddeeeghhhJkklnnoooprtttwy

Removing non-alphabetical characters

To remove all non-alphabetical characters, this solution works:

áδgÆ∞_δ¡

It is the same as the code above, followed by a filtering where each character is first doubled, and then compared its own capitalization. For example, the string "a" is converted to "aa" and then capitalized to "Aa", which is not equal to "aa". The same way, the string "B" is converted to "BB" and capitalized to "Bb", which is not equal to "BB". However, "." is converted to ".." and is unchanged when capitalized, so it will become filtered out.

Explanation

I really need more string handling in MathGolf... Right now there isn't even an operator to convert to lowercase/uppercase. The only thing I could use was the capitalization operator, which works like an uppercase operator for strings of length 1. This solution also sorts non-alphabetical characters, but those could be ignored. The alphabetical characters preserves their case and are output in the correct order.

á    sort by comparator
 δ   capitalize string
\$\endgroup\$
12
\$\begingroup\$

GolfScript, 24 / 6 characters

{26,{65+.32+}%?)},{31&}$

Example:

> Johnny walked the dog to the park.
aaddeeeghhhJkklnnoooprtttwy  

If the input is restricted to printable ascii the code can be shortened by three characters using {95&.64>\91<&}, as filter.

Can be tested here.

The can-be-ignored version is even shorter (6 chars):

{31&}$

and yields output

> Johnny walked the dog to the park.
      aaddeeeghhhJkkl.nnoooprtttwy
\$\endgroup\$
  • \$\begingroup\$ and if "alphabetize" could be construed to mean "ASCII order okay, it could just be reduced to {}$ \$\endgroup\$ – McKay Jan 29 '14 at 16:33
  • \$\begingroup\$ @McKay The question explicitely states differently. And {}$ would be equivalent to $. \$\endgroup\$ – Howard Jan 29 '14 at 16:56
  • \$\begingroup\$ Oh, yeah. Thanks, I'm trying to learn golfscript \$\endgroup\$ – McKay Jan 29 '14 at 17:16
7
\$\begingroup\$

GNU core utils - 25 characters (29 dropping symbols)

fold -1|sort -f|tr -d \\n

Example (from GNU bash 3):

$ echo "Johnny walked the dog to the park."|fold -1|sort -f|tr -d \\n
      .aaddeeeghhhJkklnnoooprtttwy   <<no trailing newline>>

From the question:

Spaces and symbols can be ignored or deleted

I chose to leave them in! To retain only alphabetic characters, replace fold -1 with grep -o \\w for +4 characters.

grep -o \\w|sort -f|tr -d \\n

Thanks to Firefly for recommending grep -o over sed, and Wumpus for fold -1. ;-)

\$\endgroup\$
  • \$\begingroup\$ This is not alphabetical order, the uppercase J should still be alphabetically sorted with the other lowercase letters. \$\endgroup\$ – aks. Jan 27 '14 at 17:27
  • \$\begingroup\$ Oh good point aks. I must add -f (fold) to sort to ignore case. \$\endgroup\$ – joeytwiddle Jan 28 '14 at 1:38
6
\$\begingroup\$

C, 121

This is quite long compared to other entries, but it does not rely on any built-in sorting or ToLower functions:

j;main(k){char s[99],*p=s;gets(s);while(*p){j=p-s-1;k=*p++;while(j>=0&&(s[j]|32)>(k|32))s[j+1]=s[j--];s[j+1]=k;}puts(s);}

More readable version:

j; main(k) {
    char s[99], *p=s;
    gets(s);
    while(*p) {
        j = p-s-1;
        k = *p++;
        while(j >= 0 && (s[j]|32) > (k|32))
            s[j+1] = s[j--];
        s[j+1] = k;
    }
    puts(s);
}

This is an implementation of insertion sort with a case-insensitive comparison between elements (using the |32 bitwise operation). This is because in ASCII encoding uppercase letters and lowercase letters only differ by the 25 bit.

\$\endgroup\$
5
\$\begingroup\$

Ruby - 33 Chars

$><<gets.chars.sort(&:casecmp)*''
\$\endgroup\$
  • \$\begingroup\$ Where is the output code? \$\endgroup\$ – John Dvorak Jan 22 '14 at 12:37
  • \$\begingroup\$ You can spare 2 characters by using *"" instead of .join. \$\endgroup\$ – manatwork Jan 22 '14 at 13:11
  • \$\begingroup\$ You could use p, but that's questionable, so just use puts. Also, $< is a shortcut for ARGF \$\endgroup\$ – Shelvacu Jan 22 '14 at 13:19
  • \$\begingroup\$ @manatwork edited... \$\endgroup\$ – shiva Jan 22 '14 at 13:45
  • \$\begingroup\$ You can spare 1 character by using $><< instead of puts as the separating space can be removed. \$\endgroup\$ – manatwork Jan 22 '14 at 13:45
5
\$\begingroup\$

PowerShell : 39

$([string[]][char[]](Read-Host)|sort)" #With spaces and symbols

Result

  .aaddeeeghhhJkklnnoooprtttwy

C# : 100

Console.Write(new string(input.ToCharArray().OrderBy(a=>char.ToLower(a)).ToArray()).Trim('.',' '));

Result

aaddeeeghhhJkklnnoooprtttwy
\$\endgroup\$
  • \$\begingroup\$ That's not a program as required by the question. \$\endgroup\$ – Howard Jan 22 '14 at 9:03
  • \$\begingroup\$ You don't need ToCharArray; String implements IEnumerable<char> \$\endgroup\$ – Rik Jan 22 '14 at 9:10
  • \$\begingroup\$ @howard so do scripts count as a program? \$\endgroup\$ – Ralf de Kleine Jan 22 '14 at 9:12
  • 1
    \$\begingroup\$ Your symbol-excluding solutions only work for the sample input. That input was only a sample (real input can also include other symbols). \$\endgroup\$ – Sander Jan 22 '14 at 15:35
  • 1
    \$\begingroup\$ @RalfdeKleine Sorry, I misspoke about sal, I don't think you can use that. But, you can get rid of the variable assignment with "$([string[]][char[]](Read-Host)|sort)". \$\endgroup\$ – Kris Harper Jan 22 '14 at 16:37
4
\$\begingroup\$

APL 16

      ⍞←A[⍋48|⎕av⍳A←⍞]
Johnny walked the dog to the park.
      aaddeeeghhhJkklnnoooprtttwy.
\$\endgroup\$
  • \$\begingroup\$ This doesn't meet the requirements, because J doesn't come before a, d, e, etc. \$\endgroup\$ – Timtech Jan 25 '14 at 17:40
  • \$\begingroup\$ Great job there +1 \$\endgroup\$ – Timtech Jan 25 '14 at 18:22
3
\$\begingroup\$

Perl6: 26 characters

Sorts output uppercase first, then lowercase, deletes symbols/whitespace

say [~] sort comb /\w/,get

If whitespace/symbols in output may be ignored too, this is only 21 characters.

say [~] get.comb.sort

This sorts case-insensitively, keeps symbols (26 chars)

say [~] get.comb.sort: &lc
\$\endgroup\$
  • \$\begingroup\$ It has to sort case-insensitively but it can ignore whitespace and symbols if preferred. \$\endgroup\$ – Timtech Jan 25 '14 at 18:24
3
\$\begingroup\$

Perl 34

Now takes input from STDIN.

print sort{lc$a cmp lc$b}<>=~/\w/g

Perl 18

If output including capitals first and symbols included is acceptable:

print sort<>=~/./g
\$\endgroup\$
  • \$\begingroup\$ I suspect you can shorten it further by taking the string from input (as per the description) instead of getting it from the cmdline. \$\endgroup\$ – breadbox Jan 22 '14 at 9:46
  • \$\begingroup\$ Oooh right you are! \$\endgroup\$ – Dom Hastings Jan 22 '14 at 9:56
2
\$\begingroup\$

Haskell, 88

import Data.List
import Data.Char
import Data.Ord
main=interact$sortBy$comparing toLower

(38 without imports from standard lib)

\$\endgroup\$
2
\$\begingroup\$

k (10 9)

Reads from stdin

x@<_x:0:0

Example

x@<_x:0:0
Johhny walked the dog to the park.
"      .aaddeeeghhhhJkklnoooprtttwy"
\$\endgroup\$
2
\$\begingroup\$

C#: 83

Console.Write(new string(Console.ReadLine().OrderBy(i=>i+"".ToLower()).ToArray()));

Update: 65

Executable in LinQPad

new string(Console.ReadLine().OrderBy(i=>i+"").ToArray()).Dump();
\$\endgroup\$
  • 1
    \$\begingroup\$ You can remove the Dump and state it runs in LinqPad's Expression Mode :) \$\endgroup\$ – Jacob Jun 30 '14 at 14:33
1
\$\begingroup\$

Python 3: 45

print(''.join(sorted(input(),key=str.lower)))
\$\endgroup\$
  • \$\begingroup\$ I'm not into Python but does your code remove the spaces en the period? \$\endgroup\$ – Ralf de Kleine Jan 22 '14 at 8:39
  • \$\begingroup\$ No, but "Spaces and symbols can be ignored or deleted", so I just ignore them! \$\endgroup\$ – evuez Jan 22 '14 at 8:43
  • \$\begingroup\$ Ah reading is difficult ;) \$\endgroup\$ – Ralf de Kleine Jan 22 '14 at 9:12
  • \$\begingroup\$ Using lambda saves some bytes: Try it Online \$\endgroup\$ – Vedant Kandoi Dec 11 '18 at 11:28
1
\$\begingroup\$

J, 12 characters

(/:32|a.i.])

Ignores any non-alpha characters.

\$\endgroup\$
  • \$\begingroup\$ This task asks for a program. I can see no I/O here. If you are using any interpreter flags, you have to state them - and count them into the character count. \$\endgroup\$ – John Dvorak Jan 22 '14 at 12:35
  • \$\begingroup\$ @JanDvorak Okay, would a function count - f=., or do you want me to add the 1!:1[1? \$\endgroup\$ – Gareth Jan 22 '14 at 12:37
  • \$\begingroup\$ 1!:1[1 and echo please \$\endgroup\$ – John Dvorak Jan 22 '14 at 12:38
  • \$\begingroup\$ @JanDvorak Why would you want echo? \$\endgroup\$ – Gareth Jan 22 '14 at 12:38
  • \$\begingroup\$ Does the J interpreter automatically output the result of the last expression when running a script file? Or, how do you run it? \$\endgroup\$ – John Dvorak Jan 22 '14 at 12:40
1
\$\begingroup\$

Javascript - 74

Unfortunately, due to the way JS sorts characters, we cannot use standard sorting function:

prompt().split("").sort(function(a,b){return a.localeCompare(b)}).join("")

Actually this can be shortened to:

prompt().split("").sort((a,b)=>a.localeCompare(b)).join("")
\$\endgroup\$
1
\$\begingroup\$

F# (68 56)

I'm learning F# so I'm sure this could be shorter:

let f s=s|>Seq.sortBy Char.ToLower|>Seq.iter(printf"%c")

Output:

> f "Johnny walked the dog to the park."
        .aaddeeeghhhJkklnnoooprtttwy 
\$\endgroup\$
1
\$\begingroup\$

PHP, 50 bytes

$a=str_split($argn);natcasesort($a);echo join($a);

does not remove non-letters, takes input from STDIN; run with -R.

\$\endgroup\$
0
\$\begingroup\$

R, 48 characters

cat(sort(unlist(strsplit(scan(,""),""))),sep="")

Example usage:

> cat(sort(unlist(strsplit(scan(,""),""))),sep="")
1: Johnny walked the dog to the park.
8: 
Read 7 items
.aaddeeeghhhJkklnnoooprtttwy
\$\endgroup\$
0
\$\begingroup\$

q/k4 (3? 5? 8?)

if it's sufficient to enter the code and the input directly into the REPL, it's just asc:

q)asc"Johnny walked the dog to the park."
`s#"      .Jaaddeeeghhhkklnnoooprtttwy"

the `s# is bit of q notation that indicates that the string is in sorted order (can be binary searched, etc.). if it has to go, that costs two characters, making five:

q)`#asc"Johnny walked the dog to the park."
"      .Jaaddeeeghhhkklnnoooprtttwy"

if you want it provided on stdin, it's time to switch to k4 (and we get rid of the `s# for free), and it's an eight-character solution:

  x@<x:0:0
Johnny walked the dog to the park.
"      .Jaaddeeeghhhkklnnoooprtttwy"

that one, btw, will work as a code file exactly as is (still eight characters, since q is fine with not having the final newline in a code file). normally there would be issues with a welcome banner and with the REPL staying open, but if you pass the input as a herestring, all that goes away:

$ cat asc.k
x@<x:0:0
$ q asc.k<<<'Johnny walked the dog to the park.'
"\n      .Jaaddeeeghhhkklnnoooprtttwy"
$ 

not actually sure where that extra newline in the output is coming from....

\$\endgroup\$
0
\$\begingroup\$

Jelly, 3 bytes

ŒlÞ

My first Jelly solution on this site! Thanks to @LeakyNun and @ErikTheOutgolfer for teaching me how to use Jelly and @Dennis for making it! :D

Explanation

ŒlÞ
  Þ Sort using the function to its left
Œl  Converts to lowercase (because it's sort alphabetically, not by codepoint)

Alternatively, ŒuÞ does the exact same thing except converting to uppercase instead.

\$\endgroup\$
0
\$\begingroup\$

Powrshell, 36 bytes

-join($args-split'\W|(.)'-ne''|sort)

Test script:

$f = {

-join($args-split'\W|(.)'-ne''|sort)

}

@(
    ,("Johnny walked the dog to the park.", "aaddeeeghhhJkklnnoooprtttwy")
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$("$result"-eq"$expected"): $result"
}

Output:

True: aaddeeeghhhJkklnnoooprtttwy
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 3 bytes

áΣl

Try it online.

Explanation:

á      # Only leave the letters of the (implicit) input-string
 Σ     # Sort those letters by:
  l    #  Their lowercase equivalent
       # (And output the result implicitly)
\$\endgroup\$
0
\$\begingroup\$

Java 10, 72 bytes (as lambda function)

s->{for(int i=64;++i<91;)for(var c:s)if((c&~32)==i)System.out.print(c);}

Try it online.

But since it's an old challenge stating full program:

Java 10, 126 bytes (as full program)

interface M{static void main(String[]a){for(int i=64;++i<91;)for(var c:a[0].toCharArray())if((c&~32)==i)System.out.print(c);}}

Try it online.

Explanation:

interface M{                        // Class
  static void main(String[]a){      //  Mandatory main method
    for(int i=64;++i<91;)           //   Loop over the uppercase alphabet
      for(var c:a[0].toCharArray()) //    Inner loop over the characters of the input
        if((c&~32)                  //     If the current character converted to uppercase,
                  ==i)              //     equals the current letter of the alphabet
          System.out.print(c);}}    //      Print the character of the input-loop
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.