[Question]
  [
**Short and sweet description of the challenge:**  
Based off [ETAOIN SHRDLU](http://en.wikipedia.org/wiki/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](https://codegolf.stackexchange.com/a/32765/16180) and [isaacg's Pyth](https://codegolf.stackexchange.com/a/32759/16180) 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](https://codegolf.stackexchange.com/a/32764/16180) at 22 chars as well as [undergroundmonorail's 75-char Python answer](https://codegolf.stackexchange.com/a/32761/16180) that got the most upvotes. Once again, thanks to everyone who participated!
  
[Answer]
# 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
```
[Answer]
# CJam, ~~21~~ 19 bytes
```
qeu:A;'[,65>{A\-,}$
```
[Try it online.](http://cjam.aditsu.net/)
### 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.
[Answer]
# 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.
```
[Answer]
# [Pyth 1.0.2](http://ideone.com/fork/aM7pmv), 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.
[Answer]
# 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('')
```
[Answer]
# GolfScript, 22 chars
```
:?91,+-26>{.32+]?\-,}$
```
[Try it online.](http://golfscript.apphb.com/?c=IyBDYW5uZWQgdGVzdCBpbnB1dDoKOyJCYXNlZCBvZmYgRVRBT0lOIFNIUkRMVSwgeW91ciBjaGFsbGVuZ2UgaXMgdG8gd3JpdGUgdGhlIHNob3J0ZXN0IHByb2dyYW0gb3IgZnVuY3Rpb24gaW4gYW55IGxhbmd1YWdlIHRoYXQgb3V0cHV0cyB0aGUgMjYgbGV0dGVycyBvZiB0aGUgRW5nbGlzaCBhbHBoYWJldCBiYXNlZCBvbiB0aGVpciBmcmVxdWVuY3kgaW4gdGhlIGlucHV0LiBZb3VyIHByb2dyYW0vZnVuY3Rpb24gd2lsbCByZWNlaXZlIGFzIGlucHV0IGEgc3RyaW5nIG9mIHRleHQsIHdoaWNoIHdpbGwgY29udGFpbiBvbmUgb3IgbW9yZSB1cHBlcmNhc2UgYW5kL29yIGxvd2VyY2FzZSBsZXR0ZXJzIGFuZCBtYXkgYWxzbyBjb250YWluIHB1bmN0dWF0aW9uLCBudW1lcmFscywgc3ltYm9scywgYW5kIG90aGVyIG5vbi1hbHBoYWJldGljIGNoYXJhY3RlcnMuIFRoZSBwcm9ncmFtL2Z1bmN0aW9uIG11c3Qgb3V0cHV0IG9ubHkgdGhlIDI2IFVQUEVSQ0FTRSBsZXR0ZXJzIG9mIHRoZSBFbmdsaXNoIGFscGhhYmV0LCBpbmNsdWRpbmcgdGhvc2UgdGhhdCBkbyBub3QgYXBwZWFyIGluIHRoZSBpbnB1dCwgb3JkZXJlZCBmcm9tIG1vc3QgdG8gbGVhc3QgZnJlcXVlbnQgYmFzZWQgb24gaG93IG1hbnkgdGltZXMgdGhleSBhcHBlYXIgaW4gdGhlIGlucHV0LiBUaGUgZnJlcXVlbmN5IGlzIGNhbGN1bGF0ZWQgY2FzZS1pbnNlbnNpdGl2ZWx5LCBidXQgdGhlIG91dHB1dCBtdXN0IGJlIGluIHVwcGVyY2FzZS4gSWYgdHdvIG9yIG1vcmUgbGV0dGVycyBoYXZlIHRoZSBzYW1lIGZyZXF1ZW5jeSwgdGhleSBtYXkgYmUgaW4gYW55IG9yZGVyLiBObyBvdGhlciBvdXRwdXQsIHN1Y2ggYXMgd2hpdGVzcGFjZSwgaXMgYWxsb3dlZC4iCgojIEFjdHVhbCBwcm9ncmFtIGNvZGU6Cjo%2FOTEsKy0yNj57LjMyK10%2FXC0sfSQ%3D)
### 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.
[Answer]
# 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"
```
[Answer]
## 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
```
[Answer]
## Perl, ~~54~~ 46 bytes
**UPDATE:** after further optimizations it could be squeezed to **46** bytes:
(thx [dennis](https://codegolf.stackexchange.com/users/12012/dennis) for `-n`/`{}` hack; [chinese perl goth](https://codegolf.stackexchange.com/users/1229/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.
[Answer]
# 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"
```
[Answer]
# 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"
```
[Answer]
# 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
}
```
[Answer]
## 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)
```
[Answer]
## 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.
[Answer]
## 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
[Answer]
## 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.
[Answer]
# [Jelly](https://github.com/DennisMitchell/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!](https://tio.run/##XVZLjhxFEN3PKXLBslR3sGyQkLAFQvY@Oiu7O6z81OSnJc7AjhUrVtyAG9hwruFF/qrG0syopyszPu@9eFGfjbW/vbx8/fPNl3/@@6N8@fvf37/7@tfHl5eXn0I0TvGeilNbsCGqxFmRM3lROvhkdDa5REUb75w0@5sylvOqfo5kkvFZPTiTUSYSPrZH76lETuoW6cEbKVM4ubApyxcTgypZZfaat@IlzJ0SiiuphlVb4dd5TVbmZlKmpNgviiw/F3I96cbkVvUueKPlFAqgyAhFPptVfcI1vhSLznSJCd/L@RZC2htxQ9SsnlHkonZLunZSoZAmA3tpS3lOrCyqKmlVby0lZNmz9J9Jc2aVguaQnguQQqc5RFL4g0w4spsoTZULk/Ih5UhL/Q4wmD2HpO7sjCcTEPtN77ABGmzJOwGn77PU3iFEYPwsqNxTNIo3wa0igLghFRMFmxtqTjwuoRngjGoMijQox4GT0LBGwnOuH3HohvLuxm/RRNCSaGfje6SlAvLgh4loksoN4a4AwQKiNOWzql8AaUt1olNYQl22An4UuaqPWQF89oBojyYzWKs40CRlfXof4gVImw3IZRM3nIHQCogTBYxrg6V2mh2Q3lh0lLJARVoXl8grF6woBEp5J7VI2KuJICIjiNS4qg/F66611qejnEUoG@s8UwkeyxG3Xf0V4YrNkTWbdB6feA9eS32f@EFOhF@kc5GtMh58PYyHGJAGI2H4ChJO03YGs8kAivLz5JFyjiE6DxuHIQwUWrRcqwIjKOYaURZbS4LQ0HyV/ZyfCj8CGo3KkhRxO2lIxq1poo5f6z0bt6MnxzLw0EOZhtDYGgg2RW8Q2OUgrYpjKKyZCvSx36F2DA/ui66qlhpy01B62FX9UJI2Cr8WAq4yHOFyt5s8BLM@tcPDPA6qBDcRgWBz6OgKAKVYKMYBzTwY7S56ul@Vc/a4I0iHsJWP/yFGzE9P5qY3ucaho5sHbvPcFF4rueSGeZKHcKOygb5THdXN2tgCj67w6reW4P8tbJ@F4T/Cka@dyzW02qUFMdcSdYjoZRYsx6/GjlrHTIWNELhZrOj0c0k5TBdvGjkMB2IRi17qA1lF6OlR7F4yQWHibr1hMRGM5iuPH7kaCxh0RBuKWUSEgPxBFT08GdPagOtiHBZ4kv76NGyM9FiQdOPmAqOPLmIZprHsZJKHdE54TXvu0FZrGWPzQeyu756KVo97cLafLbxNqZUFPvQO0FCZTDf8AezLgVrhXGwjV1ua9XJlp27djYc2yrD8422g78059Z3nAY9w1VU57iiKukxEpj8KeWiuEXjMxiyxj0b1DLiTKTfGtwM4a8KgS1ziW6Mdx4Hbab2oC5D0m9DZXfHsDGdPHZAfbxMYCRiy@Hp1HSl7eUVpI7FKvL6iNHvtu7nB2Lgd@20M22EH7XkL1FYMtsjl/vodZm7q7mAQZH0rGXpUe7EPRtY5lN0seikihOohx4IRMA/NHKu76xb3WtfLCUrhrjZbZB7HxExzaKvibR1IzdII5SDA7TXnpdsdSThERdUUATzLcnNBtI39QKBH2IgMqos064SIV28wp/XUAamvgcL7dGjpjdb/AQ "Jelly – Try It Online")
This challenge was linked to [Jelly HyperTraining](https://chat.stackexchange.com/rooms/57815/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)
[Answer]
## 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](https://codegolf.stackexchange.com/a/32770/15589) 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)
```
[Answer]
# 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](http://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
```
[Answer]
## 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(''))
)
```
[Answer]
# 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
```
[Answer]
# PHP - 105 bytes
```
<?preg_filter(~‹§æ“Ö¢‹ö,'$f[$0&ﬂ]++',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&ﬂ]++',        // 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
                       //   ﬂ 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
```
[Answer]
# 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();
    }
```
[Answer]
## 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));
> 
> ```
> 
> 
[Answer]
# 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;
    }
}
```
[Answer]
## 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;
}
```
[Answer]
# 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`.
[Answer]
**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. 
```
[Answer]
# [Ceylon](http://ceylon-lang.org/), 98 bytes
```
String f(String s)=>String(('A':26).sort(byDecreasing((Object c)=>s.uppercased.count(c.equals))));
```
[Answer]
# APL, ~~26~~ 20 characters
~~`⎕a[⍒+/⎕a∘.=('\w'⎕r'\u0')⍞]`~~
`⎕a[⍒+/⎕a∘.=1(819⌶)⍞]`
-6 thanks to Adam.
]