46
\$\begingroup\$

Short and sweet description of the challenge:
Based off ETAOIN SHRDLU, your challenge is to write the shortest program or function in any language that outputs the 26 letters of the English alphabet based on their frequency in the input.

Really long, dry and thorough specification:

  • Your program/function will receive as input a string of text, which will contain one or more uppercase and/or lowercase letters and may also contain punctuation, numerals, symbols, and other non-alphabetic characters.
  • The program/function must output only the 26 UPPERCASE letters of the English alphabet, including those that do not appear in the input, ordered from most to least frequent based on how many times they appear in the input.
  • The frequency is calculated case-insensitively, but the output must be in uppercase.
  • If two or more letters have the same frequency, they may be in any order.
  • The only other output that is allowed is optional leading or trailing whitespace, such as a trailing newline. No other output inclusing whitespace is allowed.
  • Undefined behavior is allowed for input that does not contain any letters.

Example input:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae erat velit. Mauris gravida euismod libero ut tincidunt. Phasellus elit dui, consectetur et egestas in, aliquam vitae diam. Donec eget varius ante. Vestibulum cursus diam aliquet, egestas orci quis, placerat dolor. Proin vel nisi lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam erat volutpat. Etiam libero tortor, ornare id dui eget, posuere dignissim libero. Pellentesque commodo consequat volutpat. Integer hendrerit sapien libero, vel viverra augue facilisis sit amet. Quisque consectetur eget nisl quis dignissim. Ut lacinia pretium quam a placerat.
Morbi sed interdum risus, nec pretium lectus. Morbi imperdiet est id accumsan molestie. Duis sed fermentum nisl. Nunc vitae augue mattis, dictum lectus vel, accumsan nisl. Sed ultricies adipiscing rhoncus. Vivamus eu lacus a enim venenatis eleifend. Praesent consectetur tortor non eleifend ultricies. Mauris et odio posuere, auctor erat at, fringilla est. Proin in vestibulum erat. Maecenas congue commodo ante vel varius. Sed tempus mi ut metus gravida, nec dictum libero dapibus. Morbi quis viverra elit. Ut pharetra neque eget lacus tincidunt dictum. Fusce scelerisque viverra tellus et pretium.
Fusce varius adipiscing odio. Nulla imperdiet faucibus sem, at rhoncus ipsum adipiscing vitae. Phasellus imperdiet congue lacus et mollis. Nullam egestas mauris magna, et mollis lectus varius ut. Sed sollicitudin adipiscing dolor, vel elementum elit laoreet molestie. Aliquam nec nulla vel sem ultrices ullamcorper. Nullam nec felis magna. Duis sodales orci non justo aliquam tempus. Integer mi diam, tempor sed vulputate et, varius et nunc. Vestibulum sodales ipsum id mi pharetra, ut convallis mi accumsan. Sed dictum volutpat vestibulum.
Quisque ac dolor sagittis, aliquam libero at, euismod enim. Nulla ullamcorper posuere nulla vitae varius. Nam at dolor non libero elementum pellentesque in in lorem. Fusce porttitor turpis in quam placerat varius. Donec lorem orci, condimentum eu sapien sit amet, aliquet commodo magna. Quisque sed lectus sit amet arcu euismod accumsan et non nunc. Phasellus placerat congue metus, feugiat posuere leo dictum quis. Sed ultricies feugiat eros dignissim bibendum.
Mauris scelerisque consectetur libero eget varius. Aenean neque nunc, ullamcorper vitae orci in, auctor ornare sapien. Nam lacinia molestie imperdiet. Nam vitae mattis nibh. Vestibulum consequat tellus ac nisi sagittis pulvinar. Nullam mollis ornare quam, et venenatis leo porttitor sit amet. Nulla urna neque, dignissim non orci ut, volutpat ultrices erat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque vestibulum tellus nec eros faucibus porta.

Example output:

EITUSALNROMCDPVGQBFHJKWXYZ

Note: there is a 5 way tie between KWXYZ for that input.

Edit:

The competition is over! Thanks to everyone who participated. And now for the winner(s!): Both Dennis' CJam and isaacg's Pyth answers came in at a whopping 19 characters. Taking Dennis' advice, I'm going to mark his answer as accepted because his was the first to reach 19 characters. Honorable mentions go to Ilmari Karonen's third-place Golfscript answer at 22 chars as well as undergroundmonorail's 75-char Python answer that got the most upvotes. Once again, thanks to everyone who participated!

\$\endgroup\$
8
  • \$\begingroup\$ Is frequency measured for the upper case letters of the input only? \$\endgroup\$
    – Howard
    Jun 30, 2014 at 23:06
  • \$\begingroup\$ @Howard, no, frequency is measured based on all letters but the output is in uppercase only \$\endgroup\$
    – Abraham
    Jun 30, 2014 at 23:10
  • \$\begingroup\$ If we choose to use a function, how should the byte count be taken? In JavaScript, for example, f=function(){return} could be counted as 7 bytes (inner function: return), 18 bytes (anonymous function: function(){return}) or 20 bytes (named function: f=function(){return}). \$\endgroup\$
    – Dennis
    Jul 1, 2014 at 4:40
  • \$\begingroup\$ @Dennis I think it's standard to include the function definition in the character count, so I would say go with your last example. \$\endgroup\$
    – Abraham
    Jul 1, 2014 at 10:37
  • 1
    \$\begingroup\$ What to do if there're two answers with the shortest code? suggests awarding the green checkmark to the earlier solution. isaacg posted his answer first, I golfed mine to 19 bytes first. Whichever tie breaker you pick will be fine by me, but not having an accepted answer at all is a little anti-climatic in my opinion. \$\endgroup\$
    – Dennis
    Jul 7, 2014 at 23:33

53 Answers 53

43
\$\begingroup\$

Python 2 or 3 - 77 75 bytes

f=lambda s:''.join(sorted(map(chr,range(65,91)),key=s.upper().count))[::-1]

I had an answer before that grabbed input from STDIN, but I realized it was technically invalid. I used input() which gets only a single line, but the question's example input implies that it should handle multiple lines at once. To meet spec, I turned my answer into a function that takes a string argument. To my surprise, it was two bytes smaller! It didn't occur to me that print(...) and input() were longer than f=lambda s: and s.

This also makes the answer compatible with both Python 2 and Python 3. Originally it was only Python 3, because it used input() (which was called raw_input() in 2). Now that it's a function, it works in both.

Explained

                                  range(65,91)                              # The numbers 65 to 90
                          map(chr,range(65,91))                             # Convert to ASCII

                                                    s                       # The input string
                                                    s.upper()               # Convert to uppercase
                                                    s.upper().count         # Function literal for 'how many times the argument appears in the string'

                   sorted(map(chr,range(65,91)),key=s.upper().count)        # Sort by that function
           ''.join(sorted(map(chr,range(65,91)),key=s.upper().count))       # Concatenate to string
           ''.join(sorted(map(chr,range(65,91)),key=s.upper().count))[::-1] # Step through by -1 (i.e. reverse string)

  lambda s:''.join(sorted(map(chr,range(65,91)),key=s.upper().count))[::-1] # Make it a function (`return` is implicit for lambdas)
f=lambda s:''.join(sorted(map(chr,range(65,91)),key=s.upper().count))[::-1] # Give it a name
\$\endgroup\$
9
  • 2
    \$\begingroup\$ On the other hand, the comments in the explanation make me facepalm. Welcome to CS 101! \$\endgroup\$
    – Izkata
    Jul 2, 2014 at 19:37
  • 7
    \$\begingroup\$ @Izkata The important thing is that it shows you in which order to read the code. Because the best place to start reading golfed code is rarely obvious, especially when it gets a bit more complicated or terse than this. \$\endgroup\$ Jul 2, 2014 at 21:41
  • 1
    \$\begingroup\$ Beautiful presentation! \$\endgroup\$
    – xnor
    Jul 3, 2014 at 0:07
  • 3
    \$\begingroup\$ @Izk My goal was to make it understandable to people who don't know python. I would never make comments like these in a real project. \$\endgroup\$ Jul 3, 2014 at 13:35
  • 2
    \$\begingroup\$ @imm No. count isn't a variable or anything, it's a literal function. As cool as it would be to be able to multiply a function's return value by -1 by sticking a - in front, that's not a feature python has. \$\endgroup\$ Jul 3, 2014 at 13:40
26
\$\begingroup\$

CJam, 21 19 bytes

qeu:A;'[,65>{A\-,}$

Try it online.

Example

$ cjam etaoin.cjam <<< "~XyxY YyxZ"
YXZABCDEFGHIJKLMNOPQRSTUVW

(no newline)

How it works

qeu:A; " Read from STDIN, convert to uppercase, save in the variable “A” and discard, ";
'[,    " Push an array of all ASCII characters before “[” (NUL to “Z”).               ";
65>    " Remove the first 64 characters (NUL to “@”).                                 ";
{      " Sort the array of characters by the following mapping:                       ";
  A\   " Swap the character with the string saved in variable “A”.                    ";
  -    " Remove all occurrences of the character from the string.                     ";
  ,    " Push the length of the string.                                               ";
}$     "                                                                              ";

More occurrences means more characters get removed, so the most frequent characters appear at the beginning of the array.

\$\endgroup\$
2
  • \$\begingroup\$ Very clever indeed. \$\endgroup\$
    – Abraham
    Jul 2, 2014 at 1:18
  • \$\begingroup\$ Congratulations @Dennis on winning the contest! \$\endgroup\$
    – Abraham
    Jul 7, 2014 at 22:40
15
\$\begingroup\$

Bash, 65 bytes

(tr a-z A-Z;echo {A..Z})|fold -1|sort|uniq -c|sort -nr|tr -dc A-Z

Example

$ bash etaoin.sh <<< "~AbaB BbaC"
BACZYXWVUTSRQPONMLKJIHGFED

How it works

(              #
  tr a-z A-Z   # Turn lowercase into uppercase letters.
  echo {A..Z}  # Print all uppercase letters.
) |            #
fold -1 |      # Split into lines of length 1.
sort |         # Sort those lines (required for piping to uniq).
uniq -c |      # Print the frequencies of all lines.
sort -nr |     # Sort by frequency (reversed).
tr -dc A-Z     # Remove everything that's not an uppercase letter.
\$\endgroup\$
5
  • 1
    \$\begingroup\$ This is not locale portable, you need to force LC_COLLATE=C (or shorter, LC_ALL). \$\endgroup\$
    – Chris Down
    Jul 1, 2014 at 9:17
  • 7
    \$\begingroup\$ @ChrisDown Portability isn't generally a concern in code golf answers. \$\endgroup\$
    – Kevin
    Jul 1, 2014 at 13:07
  • 1
    \$\begingroup\$ Without portability, what this answer does is not well defined. \$\endgroup\$
    – Chris Down
    Jul 1, 2014 at 13:09
  • \$\begingroup\$ @ChrisDown: I've tested a few strings and a few locales, but I couldn't find an example where uniq misbehaves for alphabetic characters. Could you show me one? \$\endgroup\$
    – Dennis
    Jul 1, 2014 at 14:34
  • \$\begingroup\$ @ChrisDown This script is portable enough to run on OpenBSD using the BSD versions of fold, sort, tr, uniq, if the shell is bash or ksh93. Other shells, like zsh, fail to expand {A..Z}. All LC_COLLATE locales work, because OpenBSD only has LC_COLLATE=C. \$\endgroup\$
    – kernigh
    Jul 2, 2014 at 17:59
12
\$\begingroup\$

Pyth 1.0.2, 19 20

=ZUwsVm;dSm[cZkk)UG

Try it here: http://ideone.com/fork/YlWpEJ

Learn more about Pyth here: http://esolangs.org/wiki/Pyth

Example:

Based off ETAOIN SHRDLU, your challenge is to write the shortest program or function in any language that outputs the 26 letters of the English alphabet based on their frequency in the input.

Gives:

TENOHARSIULGFPYDCBWQMZXVKJ

Explanation:

=ZUw: Convert input to uppercase and store in Z.

sV: Print the sum of the reverse of

m;d: The last entries of

S: Sorted by their first entry, in increasing order

m[cZkk): The lists [count of k in Z, k]

UG: For k in the uppercase letters.

Rough Python equivalent:

G='abcdefghijklmnopqrstuvwxyz'
Z=copy(upper(input()))
print(_sum(rev(_map(lambda d:d.pop(),sorted(_map(lambda k:_list(count(Z,k),k),upper(G)))))))

This is not entry, I just thought people might like to see it. In Pyth 1.0.4, the following program is a solution in 10 characters:

JUwo_cJNUG

Explanation:

JUw: Convert input to uppercase and store in J.

o: (Print) Sort by

_cJN: -1*(count of N in J)

UG: Over N in the uppercase letters.

It is not a legal solution because several of the changes from Pyth 1.0.2 to 1.0.4, including the addition of the o, sort by, function, were in response to this problem.

\$\endgroup\$
11
  • \$\begingroup\$ I suggest you to update the Pyth link to the official page of Pyth, if it exists. \$\endgroup\$
    – A.L
    Jul 1, 2014 at 2:15
  • \$\begingroup\$ @A.L. That is the official page of Pyth, until I put up an esolang entry. \$\endgroup\$
    – isaacg
    Jul 1, 2014 at 2:35
  • \$\begingroup\$ Why do you need to store the input in a variable Z to refer to it once later? Would just putting the expression for Z in its place cause input to be read multiple times? \$\endgroup\$
    – xnor
    Jul 1, 2014 at 20:53
  • \$\begingroup\$ @xnor The position Z is used in is inside a lambda function, because it is in the first argument of a map, so it needs to be saved to a variable. Using Uw there would indeed result in input being read 26 times. \$\endgroup\$
    – isaacg
    Jul 1, 2014 at 20:56
  • 1
    \$\begingroup\$ @A.L Alright, Pyth is up on both esolang and on github. The github link is at the bottom of the esolang page, which is linked in the answer. Github does code colorization. \$\endgroup\$
    – isaacg
    Jul 2, 2014 at 1:44
11
\$\begingroup\$

Javascript (ES6) 119 117

Edit: (-2) Removed the need for toUpperCase using a case-insensitive RegEx in the split call.

a=prompt(f=x=>a.split(RegExp(x,'i')).length)
alert([...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'].sort((b,c)=>f(c)-f(b)).join(''))

Alternative (same length): Condensed the sort and character counting into a single function.

a=prompt()
alert([...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'].sort(f=(b,c)=>c?f(c)-f(b):a.split(RegExp(b,'i')).length).join(''))

As a function: 105 104

Edit: (-1) Condensed the sort and character counting into a single function.

F=a=>[...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'].sort(f=(b,c)=>c?f(c)-f(b):a.split(RegExp(b,'i')).length).join('')
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Interesting technique. \$\endgroup\$
    – Matt
    Jul 1, 2014 at 4:44
  • 1
    \$\begingroup\$ Splattering a string… delightful! \$\endgroup\$
    – Bergi
    Jul 1, 2014 at 20:23
10
\$\begingroup\$

GolfScript, 22 chars

:?91,+-26>{.32+]?\-,}$

Try it online.

Explanation:

  • :? assigns the input string to the symbol ?. (I use a punctuation symbol so that the following number 91 is not parsed as part of the symbol name.)
  • 91, constructs a list of the numbers from 0 to 90 (ASCII code of Z).
  • + appends this list to the input string, thereby converting it from an array of ASCII codes to a string (and conveniently also removing the input string from the stack).
  • -26> takes the last 26 characters of this string, producing a string containing the uppercase ASCII letters from A to Z.
  • The { }$ applies the code block to all the characters in the input string, and sorts those characters according to the result.
  • Inside the code block, . duplicates the character and 32+ converts the copy from uppercase to lowercase. The ] collects these two characters into an array, ?\- takes the input string stored in ? and removes all occurrences of the characters in the array from it, and , counts the length of the remaining string, which will be the sort key. The characters will be sorted in ascending order by this key, and thus in descending order by number of occurrences.
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Looks like we had pretty much the same idea. Minor bug: The letter Z is missing. It should be 91,+-26>. \$\endgroup\$
    – Dennis
    Jul 1, 2014 at 4:03
  • \$\begingroup\$ @Dennis: Ah, oops. Fixed, although who needs that letter anyway? :) \$\endgroup\$ Jul 1, 2014 at 13:34
  • 2
    \$\begingroup\$ @IlmariKaronen Based on community feedback, I amended the rules to allow for a trailing newline (see the question for a complete description). Your score is now 22, rather than 25 :) \$\endgroup\$
    – Abraham
    Jul 1, 2014 at 20:54
8
\$\begingroup\$

Haskell, 110 bytes

import Data.List
import Data.Char
a%f=compare(f a).f
f t=sortBy(% \c->length$filter((/=c).toUpper)t)['A'..'Z']

Example usage:

λ> f "Based off ETAOIN SHRDLU, your challenge is to write the shortest program or function in any language that outputs the 26 letters of the English alphabet based on their frequency in the input."
"ETNAHORISULFGPBCDYMQWJKVXZ"
\$\endgroup\$
2
  • 1
    \$\begingroup\$ What about (/=c) and getting rid of the 0-? \$\endgroup\$
    – Lynn
    Aug 14, 2015 at 2:21
  • \$\begingroup\$ @Mauris nice catch! I edited it in and shaved off another character. \$\endgroup\$
    – Flonk
    Aug 19, 2015 at 9:52
7
\$\begingroup\$

Ruby 2.0, 53 characters

EDIT: Fixed to work correctly with multiline strings, thanks @durron597!

f=->s{$><<(?A..?Z).sort_by{|c|-s.upcase.count(c)}*''}

Creates a function called f which can be used as follows:

f['jackdaws love my big sphinx of quartzzz']

Prints to STDOUT:

AZOSICGHEJKLMBFPQRDTUVWXYN
\$\endgroup\$
2
  • 2
    \$\begingroup\$ This answer is not correct. It gives this answer: EITASUROLNCMPDVQGBHFKJWXYZ for the example in the question \$\endgroup\$
    – durron597
    Jul 1, 2014 at 19:23
  • 1
    \$\begingroup\$ @durron597 Thanks, you are correct! It wasn't handling multiline strings correctly - gets returns a line at a time. It can be fixed by changing gets to gets$n but changing it into a function is 1 char shorter. \$\endgroup\$ Jul 1, 2014 at 23:46
6
\$\begingroup\$

Perl, 54 46 bytes

UPDATE: after further optimizations it could be squeezed to 46 bytes: (thx dennis for -n/{} hack; chinese perl goth for <=>->- hack)

s/./$h{uc$&}++/eg}{say sort{$h{$b}-$h{$a}}A..Z

It is to be run with run with perl -nE

Original solution (does not need special Perl options):

s/./$h{uc$&}++/egfor<>;print sort{$h{$b}<=>$h{$a}}A..Z

Verified in Perl 5.8.3, 5.14.2

If you get a warning, separate eg and for with a space (+1 char), if you mind

example usage:

$ python -c 'import this' | perl -le 's/./$h{uc$&}++/egfor<>;print sort{$h{$b}<=>$h{$a}}A..Z' 2>/dev/null
ETAISONLRHPBUCDYMFGXVWKZJQ

EXPLANATION: On each character (.) of each input line (for<>), apply a substitution "pattern", which in fact is evaluated as an expression (e flag of the s///), that increments an upcased (uc) character (./$& is shorter than more obvious (.)/$1) count in the (uninitialized) hash (%h). Then, the letter frequency hash is used in a sort comparison function to print out upper-case alphabet in the right order.

\$\endgroup\$
9
  • 1
    \$\begingroup\$ Shorter and no error messages: perl -ne 's/./$h{uc$&}++/eg}{print sort{$h{$b}<=>$h{$a}}A..Z' \$\endgroup\$
    – Dennis
    Jul 3, 2014 at 13:45
  • \$\begingroup\$ Dennis: very interesting, it looks like a typo.. wth is this? i've had some variants using -n and END{}, but they were always longer.. feel free to update the answer, if you want \$\endgroup\$
    – mykhal
    Jul 3, 2014 at 14:02
  • 1
    \$\begingroup\$ Yes, -n wraps while(<>){...} around the code. I avoid editing other users' code. Too easy to make a mistake, some things only work on some computers, etc. \$\endgroup\$
    – Dennis
    Jul 3, 2014 at 14:25
  • 1
    \$\begingroup\$ Joe: i was talking about the }{ "injection", not just about the well known -n option. One might not expect that the code string actually technically is wrapped by the while loop code string before the execution, not only just that it somehow works like as if it was wrapped.. \$\endgroup\$
    – mykhal
    Jul 4, 2014 at 6:10
  • 1
    \$\begingroup\$ save two more chars: replace $h{$b}<=>$h{$a} with $h{$b}-$h{$a} \$\endgroup\$ Jul 7, 2014 at 10:03
5
\$\begingroup\$

R, 123 bytes

The code is improved thanks to the suggestions by @RichieCotton.

text <- "Based off ETAOIN SHRDLU, your challenge is to write the shortest program or function in any language that outputs the 26 letters of the English alphabet based on their frequency in the input."

f=function(x){b=plyr::count(toupper(strsplit(x,"")[[1]]));c=merge(LETTERS,b,all.x=T);paste(c[order(-c$freq),1],collapse="")}

f(text)

Output:

> f(text)
[1] "ETNAHORISULFGPBCDYMQWJKVXZ"
\$\endgroup\$
1
  • 1
    \$\begingroup\$ @RichieCotton: I have rejected your suggested edit twice now. I don't know if you get notified with the reason for the reject vote, so if you read this: please provide golfing improvements in comments, so the OP can review them. Here is why: meta.codegolf.stackexchange.com/a/1619/8478 \$\endgroup\$ Jul 5, 2014 at 20:46
5
\$\begingroup\$

AppleScript, 278

I noticed that "a" = "A" is true in AppleScript. I can use this in code golf, but the rest of the script is too wordy. I used AppleScript 1.8.3.

This defines a function f. If you add f("a string") at the bottom of the script and run it in the Script Editor, it will show the result.

on c(n)
ASCII character(64+n)
end
on f(s)
set{a,r}to{{},""}
repeat with i from 1 to 26
set j to 0
repeat with b in s
if b&""=c(i)then set j to j+1
end
set a to a&j
end
repeat with j from 0 to(count s)
repeat with i from 1 to 26
if a's item i=j then set r to c(i)&r
end
end
r
end

Formatted and commented:

-- Returns nth letter of alphabet.
on c(n)
    ASCII character (64 + n)
end c

-- Returns letters in s sorted by frequency.
on f(s)
    -- a: list of letter counts
    -- r: resulting string
    set {a, r} to {{}, ""}

    -- For each letter from A to Z,
    -- count letters in string s.
    repeat with i from 1 to 26
        set j to 0
        repeat with b in s
            -- Can't use b = c(i), because
            -- b is a reference to a string
            -- and = never dereferences its
            -- operands. Get contents of b,
            -- here by coercing b to string.
            if b & "" = c(i) then set j to j + 1
        end repeat
        -- Set item i of a to count j.
        set a to a & j
    end repeat

    -- Sort letters by frequency.  Do a counting sort
    -- because AppleScript lacks a sort command.
    repeat with j from 0 to (count s)
        repeat with i from 1 to 26
            if a's item i = j then set r to c(i) & r
        end repeat
    end repeat
    r
end f

-- Example call:
f("Now is the time for all good men to come to the aid of their country.")
-- Result: "OTEIRNMHLFDCAYWUSGZXVQPKJB"
\$\endgroup\$
0
4
\$\begingroup\$

C++, 185 183 179 177 bytes

Not expected to win, of course (can C++ ever win?) but a fun exercise nonetheless.

#include <algorithm>
#include <stdio.h>
int f[256],p;main(){for(p=65;p<91;p++)f[p]=p;while(~(p=getchar()))f[p&95]+=256;p=256;std::sort(f,f+p);while(p--)f[p]&95&&putchar(f[p]);}

Explanation:

#include <algorithm>         // for std::sort
#include <stdio.h>           // for getchar, putchar
int f[256],p;                // declare an array of count-prefixed chars, and a counter
main(){
    for(p=65;p<91;p++)       // 65 == 'A', 91 == the character after 'Z'
        f[p]=p;              // set the character for the slot
    while(~(p=getchar()))    // read characters until EOF
        f[p&95]+=256;        // increment the packed count for the character stripped of the 'lowercase bit'
    p=256;                   // start a countdown
    std::sort(f,f+p);        // sort the array
    while(p--)               // do the countdown
        f[p]&95 &&           // if the masked-off character is set...
          putchar(f[p]);     // print it
}
\$\endgroup\$
4
\$\begingroup\$

VBScript 181 109

Updated to use a completely different algorithm. Beats JavaScript!

Pretty:

dim b(99):i=ucase(inputbox(k))
for y=65to 90
    c=chr(y)
    a=len(replace(i,c,k))
    b(a)=c+b(a)
next
msgbox join(b,k)

Golfed:

dim b(99):i=ucase(inputbox(k)):for y=65to 90:c=chr(y):a=len(replace(i,c,k)):b(a)=c+b(a):next:msgbox join(b,k)
\$\endgroup\$
4
\$\begingroup\$

J 41 35 Bytes

(u:65+i.26)([\:[#/.~@,e.~#])toupper

Demo:

i=: 'This is a test to see whether this is still working'
(u:65+i.26)([\:[#/.~@,e.~#])toupper i
STIEHLORWAGKNBCDFJMPQUVXYZ

Explanation:

(u:65+i.26) & ( [ \: [ #/.~@,e.~#]) toupper) )
ABCDE...          |    |    |   |      uppercase the right argument
                  |    |    |   \copy from right only member from left
                  |    |     \append the left argument
                  |    \ Afterwards Count apperances of each letter
                  \ Sort the left according to the appearances

The key is to append the left array, such that all letters are available, and already in order. A funny consequence of using a noun as third tine to the fork is that it works as verb as well as as phrase.

\$\endgroup\$
4
\$\begingroup\$

Groovy - 130 123 115 112 98 92

As per @cfrick's advice (twice!):

f={('A'..'Z').collectEntries{c->[c,it.grep(~/(?i)$c/).size()]}.sort{-it.value}*.key.join()}

A small test (shamelessly stolen from @jpjacobs):

assert f('This is a test to see whether this is still working') == 
    'STIEHLORWAGKNBCDFJMPQUVXYZ'

And the proposed test is also passing

\$\endgroup\$
5
  • 1
    \$\begingroup\$ The function needs to output all 26 letters, not just those present in the input string. \$\endgroup\$ Jul 1, 2014 at 20:44
  • \$\begingroup\$ @algorithmshark, indeed, my mistake, fixed \$\endgroup\$
    – Will Lp
    Jul 1, 2014 at 21:02
  • \$\begingroup\$ f={('A'..'Z').collectEntries{c->[c,it.toUpperCase().findAll(c).size()]}.sort{-it.value}.keySet().join()} for 104 \$\endgroup\$
    – cfrick
    Jul 3, 2014 at 17:00
  • 1
    \$\begingroup\$ another 6 bytes: it.grep(~/(?i)$c/) instead of it.toUpperCase().grep(c) \$\endgroup\$
    – cfrick
    Jul 4, 2014 at 10:57
  • \$\begingroup\$ @cfrick Wow! Thanks again! That toUpperCase was bothering the hell out of me. \$\endgroup\$
    – Will Lp
    Jul 4, 2014 at 11:43
4
\$\begingroup\$

SAS - 217 (I think)

Input should be placed on the line after the cards4 statement, or on the appropriate punch cards for your system. I think this approach saves a few characters vs. attempting to quote the input.

data a;
input;
S = upcase(compress(_INFILE_,,'ak'));
do i=1 to length(S);
l=substr(S,i,1);
output;
end;
cards4;
;;;;
run;
proc sql;
select l into :o separated by '' from
(select l, 1/count(l) as f from a group by l) order by f;
quit;

I'm aware that this doesn't meet the full spec, as it only returns characters that appear in the input string. I might need to rethink this a bit.

\$\endgroup\$
1
  • \$\begingroup\$ Doesn't meet the spec, but is still cool, so +1 :D \$\endgroup\$
    – cat
    Mar 30, 2016 at 1:57
4
\$\begingroup\$

Jelly, 9 bytes

ØAŒuċ¥@ÞU

Explanation

ØAŒuċ¥@ÞU  Main Link
       Þ   Sort
ØA         The uppercase alphabet by
  Œuċ¥@    number of occurrences in the input:
  Œu       Uppercase
    ċ      Count occurrences
     ¥     Grammar: Last two links as a dyad
      @    Swap arguments
        U  Reverse (because sort sorts up)

This reads as "sort the uppercase alphabet by the number of occurrences in the input uppercased, reversed", which is a rather literal translation of the challenge :P

Try it online!

This challenge was linked to Jelly HyperTraining where we solved the challenge. I posted this because I was the first to reach 10 bytes.

-1 byte thanks to Erik the Outgolfer (JHT teacher)

\$\endgroup\$
3
  • \$\begingroup\$ 9 bytes: ØAŒuċ¥@ÞU \$\endgroup\$ Oct 24, 2017 at 19:04
  • \$\begingroup\$ @EriktheOutgolfer Oh cool, thanks! \$\endgroup\$
    – hyper-neutrino
    Oct 24, 2017 at 20:10
  • \$\begingroup\$ 8 bytes: ŒuØAċ@ÞU \$\endgroup\$
    – pxeger
    Mar 21, 2022 at 8:24
3
\$\begingroup\$

VBScript 157 156 bytes

Edit: changed msgbox(p) to msgbox p

More readable:

s=ucase(InputBox(z))    'z is empty.
L=len(s)
Dim a(255)
for i=1to L
    x=asc(mid(s,i))
    a(x)=a(x)+1
next
for t=0to L
    For i=65To 90
        If a(i)=t then p=chr(i)&p
    next
next
msgbox p

Golfed: (155 characters + 1 carriage return)

s=ucase(InputBox(z)):L=len(s):Dim a(255):for i=1to L:x=asc(mid(s,i)):a(x)=a(x)+1:next:for t=0to L:For i=65To 90:If a(i)=t then p=chr(i)&p
next:next:msgbox p

I had it at 171 earlier with code that I found more interesting, but comfortablydrei's sorting method is shorter and requires len(s), which makes a "for" shorter than the "while" for the first loop. (yawn)

's=UCase(InputBox(Z))&8 'just need any extra character.  0-7 don't work because &7 is octal

s=UCase(InputBox(Z)) 'nevermind
Dim a(999)
While Len(s)
    x=Asc(s) 'returns ascii of first char
    a(x)=a(x)-1 'going negative saves a character later...
    s=Mid(s,2) 'doesn't care if you run out of string
Wend
for j=1 to 26 'this used to be   While Len(p)<26
    For i=65To 90
        If a(i)<a(y) Then y=i 'it is barely not worth it to do a(i)+a(i+32)>a(y) here to skip the ucase() above
    Next
    p=p&Chr(y)
    a(y)=1 'if I didn't go negative this would have to be -1.  arrays default to 0.
Next
MsgBox(p)
\$\endgroup\$
3
  • \$\begingroup\$ I learned some cool tricks from this post! Thanks for the mention, too. One thing: I think for t=0 should be for t=1, otherwise you always print the whole alphabet. \$\endgroup\$ Jul 1, 2014 at 17:10
  • 1
    \$\begingroup\$ @comfortablydrei Printing the whole alphabet is required. "The program/function must output only the 26 UPPERCASE letters of the English alphabet, including those that do not appear in the input" \$\endgroup\$
    – JesterBLUE
    Jul 1, 2014 at 18:18
  • \$\begingroup\$ whoa. missed that one. then it's my mistake. thanks! \$\endgroup\$ Jul 1, 2014 at 18:20
3
\$\begingroup\$

J - 38 35 char

A function taking input on the right as a string. Not a winner, but it was fun to write.

(u:65+i.26)([\:[#/.~@,e.~#])toupper

Explained:

  • toupper is a verb in the standard library that upcases a string. That then becomes the right argument of the verb, while the left argument is the alphabet: ASCII codepoints 65 to 90.

  • [ and ,e.~#]) selects (#) those letters in the right arg (]) that are elements of (e.~) the left, and then prepends (,) the left arg ([). To wit, we keep only the uppercase chars, and add a single copy of the alphabet to the end, to make sure we catch them all.

  • #/.~@ then gives the frequencies of each character. It so happens that this is given in alphabetical order, so right afterwards we can downsort (\:) the alphabet (the left argument [).

A quick lazy example below. Feel free to try it for yourself at tryj.tk.

   (u:65+i.26)([\:[#/.~@,e.~#])toupper 'Based off ETAOIN SHRDLU, your challenge is to write the shortest program or function in any language that outputs the 26 letters of the English alphabet based on their frequency in the input.'
ETNAHORISULFGPBCDYMQWJKVXZ
\$\endgroup\$
3
\$\begingroup\$

T-SQL 178

Basically, this is my VBScript solution but implemented in SQL.

This is XML output abuse to concatenate a column. In practical use, it can be joined to an outer table to emulate GROUP_CONCAT functions in MySQL and others.

Declaring the @ variable:

DECLARE @ CHAR(1024)= 'enter your text here';

Code:

with y AS(
    SELECT UPPER(@)i,0l,91y
    UNION ALL
    SELECT i,len(replace(i,char(y-1),'')),y-1
    FROM y
    WHERE y>65
)
SELECT LTRIM(
(
    SELECT char(y)
    FROM y
    WHERE y<91
    ORDER BY l
    FOR XML PATH(''))
)
\$\endgroup\$
3
\$\begingroup\$

Perl, 78 bytes

undef$/;$i=<>;$r{$i=~s/$_//gi}.=$_ for A..Z;print$r{$_}for sort{$b<=>$a}keys%r
  • Only the 26 uppercase ASCII letters without any white space are output in frequency order.
  • Tied characters are given in alphabetic order.

Result for the example in the question:

EITUSALNROMCDPVGQBFHJKWXYZ

Ungolfed:

# read input
# ----------
undef $/; # disable input separator
$i = <>;  # $i holds the complete input as one string

# analyze
# -------
# For each uppercase letter (A upto Z) its occurences are counted
# via the number of substitutions made by s/$_//gi. The lowercase
# letter is included via modifier "i".
# 
# The occurrence count is then used as key for hash %r.
# The uppercase letter is appended to the value of that hash entry.
$r{$i =~ s/$_//gi} .= $_ for A..Z;

# output
# ------
# The hash keys are sorted numerically in reverse order by
# the specified sort function.
print $r{$_} for sort {$b<=>$a} keys %r
\$\endgroup\$
2
  • \$\begingroup\$ This might work for the example, bot not e.g. for echo -e 'x\ny\n\nz\n' output, which should return XYZABCDEFGHIJKLMNOPQRSTUVW, but yields XYABCDEFGHIJKLMNOPQRSTUVWZ instead. Guess why.. :) \$\endgroup\$
    – mykhal
    Jul 2, 2014 at 19:57
  • \$\begingroup\$ @mykhal: Fixed. \$\endgroup\$ Jul 2, 2014 at 20:11
3
\$\begingroup\$

PHP - 105 bytes

<?preg_filter(~‹§æ“Ö¢‹ö,'$f[$0&fl]++',join('',range(a,z)).$argv[1]);arsort($f);foreach($f as$l=>$F)echo$l;

Here's a hexdump, cause of the special characters:

0000000 3c 3f 70 72 65 67 5f 66 69 6c 74 65 72 28 7e dc
0000010 a4 be d2 85 a2 dc 9a 2c 27 24 66 5b 24 30 26 df
0000020 5d 2b 2b 27 2c 6a 6f 69 6e 28 27 27 2c 72 61 6e
0000030 67 65 28 61 2c 7a 29 29 2e 24 61 72 67 76 5b 31
0000040 5d 29 3b 61 72 73 6f 72 74 28 24 66 29 3b 66 6f
0000050 72 65 61 63 68 28 24 66 20 61 73 24 6c 3d 3e 24
0000060 46 29 65 63 68 6f 24 6c 3b                     
0000069

And a slightly less golfed version:

<?
preg_filter(           // regular expression
  "#[A-z]#e",          // matches every letter + 'eval' flag
  '$f[$0&fl]++',        // so this code runs for every letter
                       // $f is an array whose indices are uppercase letters
                       //   and whose values represent the number of occurences
                       // lowercase is converted to uc with the bitwise and
                       //   fl is 11011111 in binary, every bit except for 32's is set
  join('', range(a,z)) // adding abcdefghijklmnopqrstuvwxyz to the input
    .$argv[1]);        //   because not all letters have to appear in the input
arsort($f);            // sort $f in reverse, maintaining indices
foreach($f as$l=>$F)   //
  echo$l;              // print each index in order

Example:

 $ php etaoin_shrdlu.php "This function sorts an array such that array indices maintain their correlation with the array elements they are associated with."
 ATIRESHNOCYUWMDLFXZBVGPQKJ
\$\endgroup\$
5
  • \$\begingroup\$ How do the special characters in preg_filter() work? \$\endgroup\$
    – Abraham
    Jul 3, 2014 at 13:33
  • 3
    \$\begingroup\$ In PHP ~ is the bitwise NOT operator, and you can apply it to strings as well, in which case it works on every character. Furthermore, PHP is happy to parse strings of text as string literals given that there are no special characters in them (e.g. operators, $ for variables, semicolon, parantheses ...). So, writing ~‹§æ“Ö¢‹ö (the bitwise inverted version) instead of "#[A-z]#e" saves one byte, as it does not have to be quoted. \$\endgroup\$ Jul 3, 2014 at 13:42
  • \$\begingroup\$ Ah, thanks. Makes sense now. \$\endgroup\$
    – Abraham
    Jul 3, 2014 at 13:44
  • 1
    \$\begingroup\$ Insofar as anything in PHP makes sense. Holy moly. \$\endgroup\$
    – fluffy
    Jul 7, 2014 at 20:47
  • \$\begingroup\$ echo join(array_keys($f)); can save one byte \$\endgroup\$
    – Titus
    Oct 24, 2017 at 15:38
3
\$\begingroup\$

C# in LINQPad - 203 Bytes

I took a different approach to the answer of Logan Dam. I made sure first that every character in the input string is sorted by its appearance and only exists once in the output string. After that I added every missing character from the alphabet to the output string.

void e(string i){var a="";foreach(var d in i.ToUpper().GroupBy(x=>x).OrderByDescending(u=>u.Count()))if(d.Key<91&&d.Key>64){a+=d.Key;}for(int x=65;x<91;x++)if(!a.Contains((char)x)){a+=(char)x;}a.Dump();}

Sadly it wouldn't beat Logan Dam's answer if I would have made in Visual Studio.

More readable version:

void e(string i)
    {
        var a = "";
        foreach (var d in i.ToUpper().GroupBy(x => x).OrderByDescending(u => u.Count()))
        {
            if (d.Key < 91 && d.Key > 64)
            {
                a += d.Key;
            }
        }
        for (int x = 65; x < 91; x++)
        {
            if (!a.Contains((char)x))
            {
                a += (char)x;
            }
        }
        a.Dump();
    }
\$\endgroup\$
1
  • \$\begingroup\$ Yay, more LINQ love! :D \$\endgroup\$
    – ldam
    Jul 3, 2014 at 15:49
3
\$\begingroup\$

C# (and LINQ) 255 226 210 Bytes

Using Patrick Huizinga's advice, the query syntax is now shorter:

namespace System.Linq{class P{static void Main(string[]a){Console.Write((from c in(a[0]+"ABCDEFGHIJKLMNOPQRSTUVWXYZ").ToUpper()where c>'@'&&c<'['group c by c into g orderby-g.Count()select g.Key).ToArray());}}}

Explanation:

Console.Write(
    (from c //declare our range variable
       in (a[0] + "ABCDEFGHIJKLMNOPQRSTUVWXYZ").ToUpper() //declare the datasource
     where c > '@' && c < '[' //include only letters
     group c by c into g //run of the mill group by
     orderby -g.Count() //order by descending
     select g.Key //we only want the actual letters
     ).ToArray() //mash it all into an array
  );

Equivalent method syntax (217):

namespace System.Linq{class P{static void Main(string[]a){Console.Write((a[0]+"ABCDEFGHIJKLMNOPQRSTUVWXYZ").ToUpper().GroupBy(c=>c).OrderBy(c=>-c.Count()).Where(c=>c.Key>'@'&&c.Key<'[').Select(c=>c.Key).ToArray());}}}

Original post:

namespace System.Linq{class P{static void Main(string[]a){(a[0]+"ABCDEFGHIJKLMNOPQRSTUVWXYZ").ToUpper().GroupBy(c=>c).OrderByDescending(c=>c.Count()).Where(c=>c.Key>'@'&&c.Key<'[').ToList().ForEach(c=>Console.Write(c.Key));}}}

This is my first ever submission and I should be doing things at work but this just looked like so much fun because I felt like I could actually participate for once.

Explanation:

(a[0] + "ABCDEFGHIJKLMNOPQRSTUVWXYZ") //ensure each character appears once
  .ToUpper()
  .GroupBy(c => c) //get access to .Count()
  .OrderByDescending(c => c.Count())
  .Where(c => c.Key > '@' && c.Key < '[') //exclude anything other than letters
  .ToList() //Only lists have a .ForEach() :(
  .ForEach(c => Console.Write(c.Key)); //print output

I never use the method syntax for LINQ so this was a learning experience for me :) also thinking about it now I could save 2 bytes by replacing the character literals with their integer counterparts, but, meh.

Shortened thanks to tips from ProgramFOX and Num Lock :)

The equivalent query syntax (slightly longer):

(from c in (a[0]+"ABCDEFGHIJKLMNOPQRSTUVWXYZ").ToUpper() where c>'@'&&c<'[' group c by c into g orderby g.Count() descending select g.Key).ToList().ForEach(c=>Console.Write(c));
\$\endgroup\$
10
  • 1
    \$\begingroup\$ On a first look, you could save a lot of characters by naming your class just P instead of Program and string[]a instead of string[] args and c=>... instead of (c)=>.... \$\endgroup\$
    – Num Lock
    Jul 2, 2014 at 9:00
  • \$\begingroup\$ Instead of two using statements, you can also put your class inside the System.Linq namespace, and remove both using statements. Then you can save some characters and it will still work fine. \$\endgroup\$
    – ProgramFOX
    Jul 2, 2014 at 9:33
  • \$\begingroup\$ @NumLock Right, didn't even think of that :) @ProgramFOX that won't save me anything because namespace is longer than using and the two extra {}s will cost me more. \$\endgroup\$
    – ldam
    Jul 2, 2014 at 9:52
  • 1
    \$\begingroup\$ namespace System.Linq{} is clearly shorter than using System;using System.Linq; just by looking at it. The idea is to omit both usings completely. \$\endgroup\$
    – Num Lock
    Jul 2, 2014 at 10:36
  • \$\begingroup\$ Ahh yes it removes both, you're right, I was thinking it only removed the one. Thanks. \$\endgroup\$
    – ldam
    Jul 2, 2014 at 10:51
3
\$\begingroup\$

C++ 701 322 232 bytes

First version 701 bytes (idiomatic STL usage)

#define _HAS_TRADITIONAL_STL 1
#include <numeric>
#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>
#include <functional>
#include <map>
#include <set>
#define ALL(x) x.begin(), x.end()
using namespace std;
typedef istream_iterator<char> iic;typedef pair<int, char> pic;map<char, int> c;set<pic> d;
void f1(char x) {c[x]--;}
void f2(const pic &p) {d.insert(make_pair(p.second, p.first));}
int main(){string s(26, 0);stdext::iota(ALL(s), 65);copy(ALL(s), ostream_iterator<char>(cout));transform(iic(cin), iic(), back_inserter(s), toupper);for_each(ALL(s), f1);for_each(ALL(c), f2);transform(ALL(c2), ostream_iterator<char>(cout), select2nd<pic>());}

Expanded clean version :

#define _HAS_TRADITIONAL_STL 1
#include <numeric>
#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>
#include <functional>
#include <map>
#include <set>
using namespace std;

typedef istream_iterator<char> iic;
map<char, int> counts;
set<pair<int, char> > counts2;

void docount(char ch) { counts[ch]--; }
void toCounts2(const pair<char, int> &p) { counts2.insert(make_pair(p.second, p.first)); }

int main()
{
    string s(26, 0);
    stdext::iota(s.begin(), s.end(), 65);
    transform(iic(cin), iic(), back_inserter(s), toupper);
    for_each(s.begin(), s.end(), docount);
    for_each(counts.begin(), counts.end(), toCounts2);
    transform(counts2.begin(), counts2.end(), ostream_iterator<char>(cout), select2nd< pair<int, char> >());
}

The idea is to demonstrate a "proper" C++ program without any hacks. Ignore the boilerplate and the fact that this only compiles on VC++

Explanation :

We fill A to Z into a string with iota(), this ensures that when we count the occurrences, each character appears even if it's not in the input.

transform() copies character by character from standard input and puts it into the end of s after calling toupper() on each one

The count of each character is decremented in the map (by maintaining negative counts we can have descending sort without extra code)

The counts map entries are copied to a set of pairs, swapping (char, count) to (count, char). Since sets are ordered, we get them sorted by decreasing frequency count

Finally we copy the set's content to standard out, using transform, and using select2nd() to pick out only the second member of the pair.

The code is fairly readable. A C++11 solution would look much prettier, since we can use lambdas

C++11 version - no need of lambdas, but auto and range based for makes things very clean (come to think of it you can do very similar with regular C++98)

#include<iostream>
#include<iterator>
#include<map>
#include<set>
using namespace std;int main(){istream_iterator<char> b(cin),e;map<char,int> c;set<pair<int,char>> d;for(char i='A';i<='Z';++i){--c[i];}for(auto i=b;i!=e;++i){c[toupper(*i)]--;}for(auto p:c){d.insert(make_pair(p.second,p.first));}for(auto p:d){cout<<p.second;}}

Expanded version :

#include <iostream>
#include <iterator>
#include <map>
#include <set>
using namespace std;
int main()
{
    istream_iterator<char> b(cin), e;
    map<char, int> c;
    set<pair<int, char>> d;
    for(char i = 'A'; i <= 'Z'; ++i) {--c[i];}
    for(auto i = b; i != e; ++i) {c[toupper(*i)]--;}
    for(auto p : c) { d.insert(make_pair(p.second, p.first)); }
    for(auto p : d) { cout << p.second; }
}

Next iteration (why read from stdin when we have argv):

#include <set>
#include <iostream>
int c[256];int main(int n, char **s){std::set<std::pair<int,char>> d;while(*s[1]){c[toupper(*s[1]++)]--;}for(n=65;n<92;++n){d.insert(std::make_pair(--c[n],n));}for(auto p:d){std::cout<<p.second;}}

Expanded version:

#include <set>
#include <iostream>
int c[256];
int main(int n, char **s)
{
    std::set<std::pair<int, char>> d;
    while (*s[1])
    {
        c[toupper(*s[1]++)]--;
    }
    for (n = 65; n < 92; n++)
    {
        d.insert(std::make_pair(--c[n], n));
    }
    for (auto p : d)
    {
        std::cout << p.second;
    }
}
\$\endgroup\$
2
\$\begingroup\$

C++ 377

Implements qsort using letter counts in array n to sort alphabet in array A. Run via command line: golf.exe < in.txt

int n[26],c,k,N;
char A[26];
int C(const void*a,const void*b)
{
int i=(int)(*(char*)a -'A');
int j=(int)(*(char*)b -'A');
return n[j]-n[i];
}
int main()
{
for(;k<26;k++)
{
A[k]=k+'A';
}
N=sizeof(A);
c=getchar();
while(c>0)
{
c=toupper(c);
c=c-'A';
if(c>=0&&c<26)n[c]++;
c=getchar();
}
qsort(A,N,1,C);
for(k=0;k<N;k++)
{
putchar(A[k]);
}
return 0;
}
\$\endgroup\$
1
2
\$\begingroup\$

C, 117(119) bytes

x[256];m=1;char c;main(){while(c=getchar()+1)++x[c-1&95];for(;m=x[++c]<x[m]?m:c;x[m<65|m>90||c?m*!c:putchar(m)]=-1);}
  • Some inputs containing ASCII codes >= 128 will incorrectly increase letter frequencies. To fix this, replace the constant 95 with 223, at a cost of 1 extra byte.
  • This will terminate early on inputs containing the character with ASCII code 255. To fix this at the cost of 1 extra byte, change char c; to just c; and ++c to c=c+1%255.
\$\endgroup\$
2
\$\begingroup\$

PowerShell - 139 chars

First, I'm not an PowerShell expert. Pretty sure there are shorter than this. But was happy with it and decided to share.

$a = Read-host
$b = ($a.ToUpper() -replace '[^A-Z]','').ToCharArray() + (65..90|%{[char[]]$_})|Group|sort Count -desc|%{$_.Name}
-join $b

How it works:

$a = Read-host            # read from stdin and save into a string var $a
$a.ToUpper()              # Convert the string to UPPERCASE
-replace'[^A-Z]',''       # Remove all non A-Z characters from the str
(...).ToCharArray()       # Convert the inner object (string) to a Char Array
+  (65..90|%{[char[]]$_}) # Create another char array with A-Z chars expanded, 
                          #  and append it to the previous one.
|Group                    # Group the char array by value for each element, 
                          #  consolidates them and count each char occurrence. Example:
                          #  Count | Name
                          #  ----- | -----
                          #      4 | B
                          #      1 | F
                          #      2 | C 
                          #     .. | ..
                          # 
|sort Count -desc         # Sorts the previous hash-table by the 'Count' column 
                          #   in desc ordering
|%{$_.Name}               # Grab only the 'Name' column from the previous sorted hash-table. 
                          # The retuslt obj will be a simple char array again, 
                          #   with the letters in the desired order
$b = (...)                # Saves the resulting char array into a new variable $b
-join $b                  # join the resulting char array elements into a single 
                          #   string, and print it to stdout. 
\$\endgroup\$
2
\$\begingroup\$

Ceylon, 98 bytes

String f(String s)=>String(('A':26).sort(byDecreasing((Object c)=>s.uppercased.count(c.equals))));
\$\endgroup\$
2
\$\begingroup\$

APL, 26 20 characters

⎕a[⍒+/⎕a∘.=('\w'⎕r'\u0')⍞]

⎕a[⍒+/⎕a∘.=1(819⌶)⍞]

-6 thanks to Adam.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ ('\w'⎕r'\u0')1(819⌶) \$\endgroup\$
    – Adám
    Oct 24, 2017 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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