| Bytes | Lang | Time | Link |
|---|---|---|---|
| 048 | AWK | 250228T185836Z | xrs |
| 071 | Red 0.6.5 | 241129T085336Z | Galen Iv |
| 042 | Ruby | 241129T040341Z | Joon Yor |
| 050 | JavaScript Node.js | 230707T125418Z | Fhuvi |
| 054 | Clojure | 230618T162858Z | c-- |
| 025 | Vyxal j | 230618T130655Z | lyxal |
| 004 | Thunno 2 N | 230617T131931Z | The Thon |
| 041 | Arturo | 230317T005424Z | chunes |
| 016 | Pip S | 230316T194051Z | DLosc |
| 046 | Python | 230305T123457Z | GulgDev |
| 208 | Pascal | 221105T173114Z | Kai Burg |
| 042 | PowerShell Core | 221108T042117Z | Julian |
| 078 | Excel | 221017T152126Z | Engineer |
| 047 | Factor | 221017T115610Z | chunes |
| 011 | Vyxal | 221017T113630Z | DialFros |
| 010 | 05AB1E | 161202T143349Z | Magic Oc |
| 009 | Japt R | 190817T233441Z | Shaggy |
| 005 | Stax | 190817T055025Z | recursiv |
| 031 | Stax | 190816T173128Z | user8965 |
| 053 | Julia 1.0 | 190815T204422Z | Simeon S |
| 048 | Pip | 190815T165017Z | Kenzie |
| 103 | Oracle SQL | 190815T162241Z | Dr Y Wit |
| 064 | JavaScript Node.js | 190813T110646Z | Rajan Ku |
| 035 | Add++ | 190811T191148Z | caird co |
| 046 | Python 3 | 190811T152010Z | movatica |
| 449 | SuperMarioLang | 190811T140555Z | Charlie |
| 145 | Pascal FPC | 180824T143715Z | AlexRace |
| 109 | C gcc | 180329T143850Z | vazt |
| 037 | JavaScript | 180329T142150Z | Shaggy |
| 012 | Japt | 180329T144552Z | Oliver |
| 200 | Java 8 | 160624T073022Z | Kevin Cr |
| 077 | Tcl | 171119T005420Z | sergiol |
| 005 | APL Dyalog Unicode | 180304T214048Z | Adá |
| 118 | Swift 3 | 161202T135400Z | Devran C |
| 015 | Bash | 140122T230041Z | AncientS |
| 029 | Mathematica | 150221T223906Z | Martin E |
| 017 | J | 150221T222417Z | randomra |
| 071 | Smalltalk | 140216T233007Z | blabla99 |
| 068 | JavaScript 69 | 140122T214421Z | Toothbru |
| 072 | F# 49 | 140122T104031Z | Rik |
| 007 | k | 140122T121949Z | skeevey |
| 080 | JavaScript | 140125T021022Z | wolfhamm |
| 064 | Scala | 140124T211757Z | Dan G |
| 019 | Sclipting | 140124T205708Z | Timwi |
| 027 | GolfScript 30 | 140124T151646Z | Ben Reic |
| 076 | newLISP | 140124T155425Z | cormulli |
| nan | C# 178 | 140123T103444Z | gideon |
| 061 | Mathematica | 140123T143137Z | Michael |
| 076 | Python 3 | 140122T082426Z | evuez |
| 058 | Python 2 | 140122T173537Z | ToonAlfr |
| 042 | Befunge 98 31 to | 140122T083437Z | Justin |
| 049 | python 3 | 140122T150657Z | Wasi |
| 049 | PowerShell | 140122T170426Z | microbia |
| 020 | GNU core utils | 140122T085538Z | joeytwid |
| 090 | Python 2 | 140122T151106Z | Paul Bis |
| 053 | Ruby 1.9.3 | 140122T100511Z | manatwor |
| 129 | C# | 140122T142543Z | Abbas |
| nan | 140122T113432Z | VisioN | |
| nan | 140122T112048Z | Aviv | |
| 022 | J | 140122T122952Z | Gareth |
| 093 | Haskell | 140122T120607Z | vek |
| 054 | Perl 5 | 140122T112838Z | protist |
| 030 | R | 140122T105253Z | plannapu |
| 015 | APL | 140122T102912Z | marinus |
| 021 | Perl 6 | 140122T101600Z | Ayiko |
| 023 | J | 140122T093200Z | FireFly |
| 072 | Windows Command Script 72 Bytes | 140122T091935Z | Robert S |
| 039 | PHP 68 or | 140122T090722Z | primo |
| 063 | Powershell | 140122T090150Z | Danko Du |
Red 0.6.5, 71 bytes
m: #[]foreach c input[m/:c: 1 + any[m/:c 0]]foreach[k v]m[print[k":"v]]
Note: The 71-bytes version works in Red 0.6.5. The Red version at TIO (Red 0.6.4) doesn't recognise input, that's why I declared it as a word. The map syntax was changed in Red 0.6.5 from #() to #[] to follow the convention that blocks [] are not initially evaluated. Strangely foreach iterator gives an error for map in TIO and that's why I convert the map to a block to[]m in order to print it according to the rules.
Red, 75 bytes
m: #()foreach c input[m/:c: 1 + any[m/:c 0]]foreach[k v]to[]m[print[k":"v]]
Ruby, 42 bytes
->s{s.chars.tally.map{puts _1+" : #{_2}"}}
If the output format wasn't so strict you could go way shorter
Ruby, 20 bytes
->s{p s.chars.tally}
JavaScript (Node.js), 50 bytes
Heavily inspired by @Shaggy 's work.
Would be 34 bytes if it were acceptable to have an unwanted string [Function: g] contained in the output ( by having &&g at the end instead of &&Object.entries(g) ).
s=>[...s].map(g=c=>g[c]=-~g[c])&&Object.entries(g)
Vyxal j, 20 bitsv1, 2.5 bytes
ĊvṄ
Given that any character can be used, I figured I'd add an answer that doesn't have strict IO.
Explained
ĊvṄ
Ċ # Counts of characters
vṄ # each joined on spaces
Thunno 2 N, 4 bytes
ƈıðj
Uses as the separator, like a lot of the other answers.
Thunno 2 N, 6 bytes
ƈı`: j
Uses : as the separator, like the challenge asks.
Explanation
ƈıðj # Implicit input
ƈ # Produce a list of [item, count] pairs for
# each unique character in the input string
ı # Map over this list of pairs:
ðj # Join the pair by a space
# Implicit output, joined by newlines
ƈı`: j # Implicit input
ƈı # As above
`: j # Join the pair by ": "
# Implicit output, joined by newlines
Pip -S, 16 bytes
{[a':aNy]}MUQ Yq
Explanation
{[a':aNy]}MUQ Yq
q ; Read a line of stdin
Y ; Yank it into the global variable y
UQ ; Remove duplicates
{ }M ; Map this function to each character:
[ ] ; Return a list containing:
a ; The character
': ; A colon
aNy ; The number of times the character appears in y
; The result is a list of lists; the -S flag joins each sublist
; on spaces and then joins the whole thing on newlines before
; printing it
With looser I/O requirements, this could be 12 bytes:
_AE(_Na)MUQa
Pascal, 208 B
See also Free Pascal.
This is a complete program according to ISO standard 10206 “Extended Pascal” though.
Note, this program does not count newlines.
The variable input possesses the built-in data type text, which automatically converts any newline indicator (sometimes it’s CR, sometimes LF, sometimes CR+LF, other times something completely differently) into a single space character (' ').
In order to distinguish between a space character as part/payload of a line vs. a space character terminating a line you’ll have to query EOLn.
program p(input,output);var c:char;s:array[char]of integer value[otherwise 0];begin while not EOF do begin read(c);s[c]:=s[c]+ord(not EOLn)end;for c:=chr(0)to maxChar do if 0<s[c]then writeLn(c:2,s[c]:9)end.
Ungolfed and annotated version:
program characterCount(input, output);
var
c: char;
spreadsheet: array[char] of integer value [otherwise 0];
begin
{ `EOF` is shorthand for `EOF(input)`. }
while not EOF do
begin
{ `read(c)` is shorthand for `read(input, c)`. }
read(c);
{ If we are `read`ing from a `text` file like `input`,
newlines are converted to a single space character.
This is avoiding the drama of LF vs. CR vs. CR+LF.
Therefore we’ll need to check `EOLn` so we aren’t
counting line-terminating spaces (the value of `c`). }
spreadsheet[c] := spreadsheet[c] + ord(not EOLn)
end;
{ Note, in Pascal `for`-loop limits are inclusive.
The constant `maxChar` is introduced in Extended Pascal. }
for c := chr(0) to maxChar do
begin
if 0 < spreadsheet[c] then
begin
writeLn(c:2, spreadsheet[c]:9)
end
end
end.
See also RosettaCode’s Letter frequency task.
PowerShell Core, 42 bytes
$input|% t*y|group|%{$_.Name+":"+$_.Count}
Converts the input into an array of characters
Group them and builds a string like <char>:<count> for each of them
Excel, 78 bytes
=LET(c,CHAR(ROW(1:255)),q,LEN(A1)-LEN(SUBSTITUTE(A1,c,)),FILTER(c&": "&q,q>0))
Input is in cell A1. Output is wherever the formula is.
LET(~)stores values as variables that can be referenced later. The last term is the output.c,CHAR(ROW(1:255))stores the extended ASCII table asc.q,LEN(A1)-LEN(SUBSTITUTE(A1,c,))stores a listqof how much shorter the input would be if you removed each ASCII character in turn.FILTER(c&": "&q,q>0)combinescandqinto the desired output format and then filters the list to just show those that actually appear in the input.
05AB1E, 10 bytes
ÙvyD¹s¢‚})
The definition of insanity is quoting the same phrase again and again and not expect despair.
[['T', 1], ['h', 3], ['e', 8], [' ', 15], ['d', 4], ['f', 2], ['i', 10], ['n', 10], ['t', 6], ['o', 4], ['s', 5], ['a', 10], ['y', 1], ['q', 1], ['u', 1], ['g', 3], ['m', 1], ['p', 3], ['r', 2], ['x', 1], ['c', 1], ['.', 1]]
Stax (31 bytes)
âpWhuÉñ♫∩Ω╝YT>ⁿë╘Æ↨»╧óPÜ≤♪Ñû1♫à
Try it online here: https://staxlang.xyz/#p=837057687590a40eefeabc59543efc89d49217afcfa2509af30da596310e85&a=1
It has some limitations. No uppercase letters, and it shows all letters, even if they have zero occurences
Unpacked version:
0]6{c+}*,""/{|3b@^&FVw""/{[cp':p|3@PF
^a ^b ^c ^d
Section A prepares a list to put the values in. Section B Gets user input. Section C counts letters, and section D outputs the result
Oracle SQL, 103 bytes
select substr(x,level,1),count(*)from t connect by level<=length(x)group by substr(x,level,1)order by 1
Test in SQL*PLus
SQL> set pages 100
SQL> set heading off
SQL> with t(x) as (select 'The definition of insanity is quoting the same phrase again and again and not expect despair.' from dual)
2 select substr(x,level,1),count(*)from t connect by level<=length(x)group by substr(x,level,1)order by 1
3 /
15
. 1
T 1
a 10
c 1
d 4
e 8
f 2
g 3
h 3
i 10
m 1
n 10
o 4
p 3
q 1
r 2
s 5
t 6
u 1
x 1
y 1
22 rows selected.
JavaScript (Node.js), 64 bytes
e=>(d={},e.replace(/\S/g,e=>d[e]=d[e]+1||1),[Object.entries(d)])
JavaScript (Node.js), 59 bytes
e=>(d={},[...e].map(e=>d[e]=d[e]+1||1),[Object.entries(d)])
Add++, 35 bytes
D,g,@@#,€=b+": "$J
D,f,@,qdA€gBcBJn
Defines a function f, which takes the input as an argument, and returns the complete formatted string.
Explanation
D,g, ; Define a helper function, g
@@#, ; that takes 2 arguments Stack: ['l' 'Hello World']
€= ; Compare each letter to argument Stack: [[0 0 1 1 0 0 0 0 0 1 0]]
b+ ; Sum Stack: [3]
": "$ ; Prepend ': ' Stack: [': ' 3]
J ; Join together Stack: [': 3']
; Return: ': 3'
D,f, ; Define a main function, f
@, ; that takes 1 argument Stack: ['Hello World']
qd ; Push two copies of unique letters Stack: [['H' 'e' 'l' 'o' ' ' 'W' 'r' 'd'] ['H' 'e' 'l' 'o' ' ' 'W' 'r' 'd']]
A ; Push the argument Stack: [['H' 'e' 'l' 'o' ' ' 'W' 'r' 'd'] ['H' 'e' 'l' 'o' ' ' 'W' 'r' 'd'] 'Hello World']
€g ; Apply g to each unique letter Stack: [['H' 'e' 'l' 'o' ' ' 'W' 'r' 'd'] [': 1' ': 1' ': 3' ': 2' ': 1' ': 1' ': 1' ': 1']]
Bc ; Zip together Stack: [['H' ': 1'] ['e' ': 1'] ['l' ': 3'] ['o' ': 2'] [' ' ': 1'] ['W' ': 1'] ['r' ': 1'] ['d' ': 1']]
BJn ; Join all togther, then with newlines
; Return the full string
SuperMarioLang, 449 bytes
>++++)
>^====+ (+++<
>,[!^= (< +======" *-<
"==#= =" + ) ======"
>%+>[!%+ ) >&[!
"====# + ) "==#=====================
! <>+++(-[!))+(%> [!!
#================#====="==##
> (((++*)+*)&+)[!
"========================#
!)*-&)*-&)*-&)*-&.(((:)).(.(<
#==========================="
Pascal (FPC), 145 bytes
var c:char;a:array[0..255]of word;i:word;begin repeat read(c);Inc(a[ord(c)])until eof;for i:=0to 255do if a[i]>0then writeln(chr(i),':',a[i])end.
C (gcc), 115 109 bytes
-6 bytes from @ceilingcat
a[256];main(c,v)char**v;{for(;--c;)for(;*v[c];)a[*v[c]++]++;for(;c<256;)a[++c]&&printf("%c : %d\n",c,a[c]);}
Takes input as command line argument.
JavaScript, 44 37 bytes
s=>[...s].map(x=>o[x]=-~o[x],o={})&&o
Try it
o.innerText=JSON.stringify((f=
s=>[...s].map(x=>o[x]=-~o[x],o={})&&o
)(i.value="The definition of insanity is quoting the same phrase again and again and not expect despair."));oninput=_=>o.innerText=JSON.stringify(f(i.value))
<input id=i><pre id=o></pre>
Japt, 12 bytes
q
â ®+S+Uè¥Z
Explanation:
q
â ®+S+Uè¥Z
| Set U to:
q | Input, split into an array of chars
â | Return all unique items in U
® | Map through the items; Z = iterative item
+S+ | Z + " " +
Uè¥Z | Number of times where Z appears in U
Java 8, 273 253 249 246 239 200 bytes
interface I{static void main(String[]a){int m[]=new int[999],i=0;for(int c:new java.util.Scanner(System.in).nextLine().getBytes())m[c]++;for(;++i<999;)if(m[i]>0)System.out.printf("%c: %d%n",i,m[i]);}}
-24 bytes thanks to @Poke.
-7 bytes thanks to @OlivierGrégoire.
Explanation:
interface I{ // Class
static void main(String[]a){ // Mandatory main-method
int m[]=new int[999], // Integer-array to count the occurrences
i=0; // Index-integer, starting at 0
for(int c:new java.util.Scanner(System.in).nextLine().getBytes())
// Loop over the input as bytes:
m[c]++; // Increase the occurrence-counter of the char by 1
for(;++i<999;) // Loop over the array:
if(m[i]>0) // If the current character occurred at least once:
System.out.print("%c: %d%n",// Print with proper formatting:
i, // The character
m[i]);}} // and the occurrence-count
Tcl, 77 bytes
lmap c [split [gets stdin] ""] {dict inc D $c}
dict ma k\ v $D {puts $k:\ $v}
APL (Dyalog Unicode), 5 bytesSBCS
Full program body. Prompts for a string from STDIN and prints newline separated table to STDOUT. Leftmost column is the input characters, and counts are right-aligned with the largest number separated from its character by a single space.
,∘≢⌸⍞
⍞ prompt for text input from STDIN
⌸ create a keys' table consisting of
, the unique element followed
∘ by
≢ the tally of the indices of its occurrence (i.e how many times it occurs)
Swift 3: 122 120 118 chars
_=readLine()!.characters.reduce([Character:Int]()){var r=$0;r[$1]=($0[$1] ?? 0)+1;return r}.map{print("\($0): \($1)")}
After running, it waits for user input.
Input
The definition of insanity is quoting the same phrase again and again and not expect despair.
Result
p: 3
n: 10
.: 1
f: 2
o: 4
u: 1
q: 1
d: 4
t: 6
x: 1
a: 10
i: 10
T: 1
m: 1
r: 2
c: 1
s: 5
e: 8
: 15
g: 3
y: 1
h: 3
Explanation
_=is necessary otherwise you'll get a warning:result of call to 'map' is unused- removing whitespace from
($0[$1] ?? 0)will result in an error, because swift recognizes?as an optional chaining operator.
Thanks to @ais523 for pointing out that there are too many whitespace characters left
Bash (20 15 characters)
ptx -S.|uniq -c
10 a
1 c
4 d
8 e
2 f
3 g
3 h
10 i
1 m
10 n
4 o
3 p
1 q
2 r
5 s
6 t
1 T
1 u
1 x
1 y
ASCII encoding now supported
Bash (23 characters):
xxd -p -c1|sort|uniq -c
1 0a
15 20
1 2e
1 54
10 61
1 63
4 64
8 65
2 66
3 67
3 68
10 69
1 6d
10 6e
4 6f
3 70
1 71
2 72
5 73
6 74
1 75
1 78
1 79
ASCII formatting not supported
Mathematica, 34 29 bytes
Not sure why the other Mathematica answer is so complicated... ;)
Grid@Tally@Characters@Input[]
J, 17 bytes
(Outputs the result exactly in the expected format.)
({.,': ',".@#)/.~
Example:
(({.,': ',":@#)/.~) 'The definition of insanity is quoting the same phrase again and again and not expect despair.'
T: 1
h: 3
e: 8
...
Shorter alternatives:
9 bytes:
({.;#)/.~
(({.;#)/.~) 'The definition of insanity is quoting the same phrase again and again and not expect despair.'
┌─┬──┐
│T│1 │
├─┼──┤
│h│3 │
├─┼──┤
│e│8 │
...
7 bytes:
~.;#/.~
(~.;#/.~)'The definition of insanity is quoting the same phrase again and again and not expect despair.'
┌──────────────────────┬───────────────────────────────────────────────┐
│The dfintosayqugmprxc.│1 3 8 15 4 2 10 10 6 4 5 10 1 1 1 3 1 3 2 1 1 1│
└──────────────────────┴───────────────────────────────────────────────┘
Here the output is a list of characters (i.e. string) and a list of occurrences of the corresponding characters.
Smalltalk, 71
Stdin nextLine asBag valuesAndCountsDo:[:c :n|(c,' : ')print.n printNL]
JavaScript (69 68 characters):
Expects s to hold the string.
_={};for(x in s)_[a=s[x]]=-~_[a];for(x in _)console.log(x+': '+_[x])
This follows the new rules perfectly.
Note: This presumes a clean environment, with no custom properties on any standard object prototypes.
Edit: 1 character less!
Console output:
T: 1
h: 3
e: 8
: 15
d: 4
f: 2
i: 10
n: 10
t: 6
o: 4
s: 5
a: 10
y: 1
q: 1
u: 1
g: 3
m: 1
p: 3
r: 2
x: 1
c: 1
.: 1
Old answer (44 characters):
r={};[].map.call(s,function(e){r[e]=-~r[e]})
This was valid before the rules changed.
r contains the output.
F# (66 59 49, 72 with prescribed formattting)
let f s=s|>Seq.countBy(id)|>Seq.iter(printfn"%A")
Output:
> f The definition of insanity is quoting the same phrase again and again and not expect despair.
(' ', 15)
('.', 1)
('T', 1)
('a', 10)
('c', 1)
('d', 4)
('e', 8)
('f', 2)
('g', 3)
('h', 3)
('i', 10)
('m', 1)
('n', 10)
('o', 4)
('p', 3)
('q', 1)
('r', 2)
('s', 5)
('t', 6)
('u', 1)
('x', 1)
('y', 1)
With the prescribed formatting, it becomes:
let f s=s|>Seq.countBy(id)|>Seq.iter(fun(a,b)->printfn"\"%c\" : %d"a b)
k (8 7)
#:'=0:0
Example
k)#:'=:0:0
The definition of insanity is quoting the same phrase again and again and not expect despair.
T| 1
h| 3
e| 8
| 15
d| 4
f| 2
i| 10
n| 10
t| 6
o| 4
s| 5
a| 10
y| 1
q| 1
u| 1
g| 3
m| 1
p| 3
r| 2
x| 1
c| 1
.| 1
edit: Down to seven, H/T Aaron Davies
Explanation
Take a String from keyboard :
k)0:0
text
"text"
Group the distinct elements and return a map containing key as distinct characters and values are the indices where the distinct elements occur.
k)=0:0
text
t| 0 3
e| ,1
x| ,2
Now count values of each entry in the map.
k)#:'=0:0
text
t| 2
e| 1
x| 1
JavaScript, 80
// 80
t=prompt(n={});for(i=0;c=t[i++];)n[c]=-~n[c];for(k in n)console.log(k+': '+n[k])
// 47 - wrong format, no prompt
for(i in a=t.split('').sort())console.log(a[i])
Scala, 64 chars
readLine.groupBy(y=>y).foreach(g=>println(g._1+" : "+g._2.size))
Sclipting, 19 characters
梴要⓶銻꾠⓷❸虛變梴❶⓺減負겠⓸⓸終丟
Output
T:1
h:3
e:8
:15
d:4
f:2
i:10
n:10
t:6
o:4
s:5
a:10
y:1
q:1
u:1
g:3
m:1
p:3
r:2
x:1
c:1
.:1
If you want the spaces around the :, change 꾠 to 긃똠, making it 20 characters.
Explanation
Get length of input string.
梴
Stack is now [ input, length ]
While {
要
Get first character of string and push ":"
⓶銻꾠
Stack is now [ length, input, firstchar, ":" ]
Replace all occurrences of that character with empty string
⓷❸虛變
Stack is now [ length, firstchar, ":", reducedinput ]
Get the length of that, calculate difference to previous length, push "\n"
梴❶⓺減負겠
Stack is now [ firstchar, ":", reducedinput, newlength, diff, "\n" ]
Move the input string and length back up, leaving output below it
⓸⓸
Stack is now [ firstchar, ":", diff, "\n", reducedinput, newlength ]
`------------------------' `-------'
Every iteration of the The length provides
While loop generates the While loop's
a bit like this terminating condition
} End While
終
Discard the length which is now 0
丟
GolfScript 30 27
:x.|{.{=}+x\,,`': '\n]''+}/
Explanation:
:x #Assign the input string to a variable x
.| #Copy the input string, and then OR it with itself to get the unique characters
Now, for each distinct character, we will perform the {.{=}+x\,,``': '\n]''+} block. For example, for the first iteration, the character will be 'T'.
.{=}+ #Generate the equality checking block. {'T'=} is left on the stack
x #Put the input string on the stack.
\ #Flip the top elements So the stack is now the input strick followed by the equality checking block.
, #Filter the input string by the equality checking block.
, #Count the number of equal characters.
`': '\n #Format the string and add a newline character
] #Collect the elements into an array
''+ #Convert the array into a string
newLISP - 76 characters
(bayes-train(explode(read-line))'D)(map(fn(f)(println(f 0) ": "(f 1 0)))(D))
Reads from keyboard, builds a Bayes-trained context namespace, then outputs entries. It's hard to golf with the handicap of readable function names... :)
C# (178 220 chars)
Based on @Spongeman's comment I changed it up a bit:
using C=System.Console;using System.Linq;class P{static void Main()
{C.WriteLine(string.Join("\n",C.ReadLine().GroupBy(x=>x)
.OrderBy(x=>x.Key).Select(g=>g.Key+":"+g.Count())));}}
Line breaks added for readability, my first feeble attempt at code golf! :)
class P {static void Main(){var d=new Dictionary<char,int>();
Console.ReadLine().ToList().ForEach(x=>{ if(d.ContainsKey(x))
{d[x]++;}else{d.Add(x,1);}});Console.WriteLine(string
.Join("\n",d.Keys.Select(x=>x+":" +d[x])));}}
Mathematica, 61 bytes
Map[{#[[1]], Length@#} &, Gather@Characters[Input[]]] // TableForm
It then pops up this dialog box,

and for the sample sentence, produces as output

Python 3: 76 characters
76
import collections as c
for x,y in c.Counter(input()).items():print(x,':',y)
44
(print same characters many times, see Wasi's answer for a valid version)
a=input()
for x in a:print(x,':',a.count(x))
Python 2, correctly (58)
s=raw_input()
for l in set(s):print l+" : "+str(s.count(l))
Output:
python count.py
The definition of insanity is quoting the same phrase again and again and not expect despair.
: 15
. : 1
T : 1
a : 10
c : 1
e : 8
d : 4
g : 3
f : 2
i : 10
h : 3
m : 1
o : 4
n : 10
q : 1
p : 3
s : 5
r : 2
u : 1
t : 6
y : 1
x : 1
Python 2, cheetah style (41)
s=input()
print {l:s.count(l) for l in s}
Output:
python count.py
"The definition of insanity is quoting the same phrase again and again and not expect despair."
{' ': 15, '.': 1, 'T': 1, 'a': 10, 'c': 1, 'e': 8, 'd': 4, 'g': 3, 'f': 2, 'i': 10, 'h': 3, 'm': 1, 'o': 4, 'n': 10, 'q': 1, 'p': 3, 's': 5, 'r': 2, 'u': 1, 't': 6, 'y': 1, 'x': 1}
Befunge 98 - 31 to 42 chars
This does not print the spaces, and only prints for characters in the string (once for each character, even duplicates). So an input of aa will produce an output of:
a:2
a:2
31 chars
~::1g1+\1p;,a.- 'g1,:',:@j`0:;#
The following seems to match almost exactly. It outputs only one time for each character, in the order they appear in the string. An input of Bbaa gives an output of
B:1
b:1
a:2
38 chars
~:1g' `j::1g1+\1p;,a.- 'g1,:',:@j`0:;#
The following prints the spaces exactly as in the output example. It also outputs every single ascii character's count, which, since it is not clearly specified, I'll say is valid.
42 chars
~:1g1+\1p;,a+1.- 'g1:,,:,," : ",:@j!`~':;#
python 3, 49
Stealing idea from evuez
t=input()
for i in set(t):print(i,':',t.count(i))
input:
The definition of insanity is quoting the same phrase again and again and not expect despair.
output:
: 15
. : 1
T : 1
a : 10
c : 1
e : 8
d : 4
g : 3
f : 2
i : 10
h : 3
m : 1
o : 4
n : 10
q : 1
p : 3
s : 5
r : 2
u : 1
t : 6
y : 1
x : 1
PowerShell (49)
[char[]](read-host)|group|%{$_.Name+":"+$_.Count}
GNU core utils - 29 22 20 chars (53 with formatting)
Wumpus's improvement (20 chars):
fold -1|sort|uniq -c
Firefly's improvement (22 chars):
grep -o .|sort|uniq -c
joeytwiddle's original (29 chars):
sed 's+.+\0\n+g'|sort|uniq -c
Originally I used sed to simply add a newline after each character. Firefly improved on that with grep -o ., since -o displays every matched pattern on its own line. Wumpus pointed out a further improvement using fold -1 instead. Nice work!
uniq does the real work, although it only applies to sorted lists.
Note that the output format does not exactly match the example in the question. That requires a final run through sed to swap the arguments. (Waiting on an answer to Jan Dvorak's question to see if this is required...)
Reformatting with sed is "only" another 33 characters! (Total 53)
|sed 's/ *\(.*\) \(.\)/\2 : \1/'
Awk can almost do the job whilst adding only 25 chars, but it hides the first space. Silly awk!
|awk '{print $2" : "$1}'
I wonder if improvements can be made in the reformatting stage...
Python 2 (90 chars)
import collections as c;print"\n".join("%s %s"%i for i in c.Counter(raw_input()).items())
Output when run on its own source:
8
" 4
% 3
) 4
( 4
. 3
; 1
C 1
\ 1
_ 1
a 2
c 4
e 3
f 1
i 9
j 1
m 2
l 2
o 6
n 7
p 3
s 5
r 5
u 2
t 6
w 1
Ruby 1.9.3: 53 characters
(Based on @shiva's and @daneiro's comments.)
gets.split("").uniq.map{|x|puts x+" : #{$_.count x}"}
Sample run:
bash-4.1$ ruby -e 'a=gets;a.split("").uniq.map{|x|puts"#{x} : #{a.count x}"}' <<< 'Hello world'
H : 1
e : 1
l : 3
o : 2
: 1
w : 1
r : 1
d : 1
: 1
Ruby: 44 characters
Not respecting the output format:
s=Hash.new 0;gets.chars{|c|s[c]+=1};pp s
Sample run:
bash-4.1$ ruby -rpp -e 's=Hash.new 0;gets.chars{|c|s[c]+=1};pp s' <<< 'Hello, world!'
{"H"=>1,
"e"=>1,
"l"=>3,
"o"=>2,
","=>1,
" "=>1,
"w"=>1,
"r"=>1,
"d"=>1,
"!"=>1,
"\n"=>1}
C#: 129
This is Avivs answer but shorter:
var s=Console.ReadLine();for(int i=0;i<256;i++){var ch=(char)i;Console.Write(s.Contains(ch)?ch+":"+s.Count(c=>c==ch)+"\r\n":"");}
This is mine:
C#: 103
foreach(var g in Console.ReadLine().OrderBy(o=>o).GroupBy(c=>c))Console.WriteLine(g.Key+":"+g.Count());
JavaScript
6653 bytes:prompt(a={}).replace(/./g,function(c){a[c]=-~a[c]}),a6956 bytes:b=prompt(a={});for(i=b.length;i--;){a[b[i]]=-~a[b[i]]};a7865 bytes:prompt().split('').reduce(function(a,b){return a[b]=-~a[b],a},{})
N.B.: In all cases deleted number of bytes refer to extra console.log() call which is pointless if run in the console. Big thanks to @imma for the great catch with -~a[b] and prompt(a={}). This definitely saved some more bytes.
C#
string str = Console.ReadLine(); // Get Input From User Here
char chr;
for (int i = 0; i < 256; i++)
{
chr = (char)i; // Use The Integer Index As ASCII Char Value --> Convert To Char
if (str.IndexOf(chr) != -1) // If The Current Char Exists In The Input String
{
Console.WriteLine(chr + " : " + str.Count(x => x == chr)); // Count And Display
}
}
Console.ReadLine(); // Hold The Program Open.
In Our Case, If The Input Will Be "The definition of insanity is quoting the same phrase again and again and not expect despair."
The Output Will Be:
: 15
. : 1
T : 1
a : 10
c : 1
d : 4
e : 8
f : 2
g : 3
h : 3
i : 10
m : 1
n : 10
o : 4
p : 3
q : 1
r : 2
s : 5
t : 6
u : 1
x : 1
y : 1
J, 22 characters
(~.;"0+/@(=/~.))1!:1]1
Example:
(~.;"0+/@(=/~.))1!:1]1
The definition of insanity is quoting the same phrase again and again and not expect despair.
+-+--+
|T|1 |
+-+--+
|h|3 |
+-+--+
|e|8 |
+-+--+
| |15|
+-+--+
|d|4 |
+-+--+
|f|2 |
+-+--+
|i|10|
+-+--+
|n|10|
+-+--+
|t|6 |
+-+--+
|o|4 |
+-+--+
|s|5 |
+-+--+
|a|10|
+-+--+
|y|1 |
+-+--+
|q|1 |
+-+--+
|u|1 |
+-+--+
|g|3 |
+-+--+
|m|1 |
+-+--+
|p|3 |
+-+--+
|r|2 |
+-+--+
|x|1 |
+-+--+
|c|1 |
+-+--+
|.|1 |
+-+--+
Haskell, 93
import Data.List
main=getLine>>=mapM(\s->putStrLn$[head s]++" : "++show(length s)).group.sort
Perl 5, 54 characters
map{$h{$_}++}split//,<>;print"$_ : $h{$_}\n"for keys%h
R, 30 characters
table(strsplit(readline(),""))
Example usage:
> table(strsplit(readline(),""))
The definition of insanity is quoting the same phrase again and again and not expect despair.
. a c d e f g h i m n o p q r s t T u x y
15 1 10 1 4 8 2 3 3 10 1 10 4 3 1 2 5 6 1 1 1 1
APL (15)
M,⍪+⌿Z∘.=M←∪Z←⍞
If you really need the :, it's 19 (but there's others who aren't including it):
M,':',⍪+⌿Z∘.=M←∪Z←⍞
Output:
M,⍪+⌿Z∘.=M←∪Z←⍞
The definition of insanity is quoting the same phrase again and again and not expect despair.
T 1
h 3
e 8
16
d 4
f 2
i 10
n 10
t 6
o 4
s 5
a 10
y 1
q 1
u 1
g 3
m 1
p 3
r 2
x 1
c 1
. 1
Perl 6: 21 chars
.say for get.comb.Bag
(REPL) > .say for get.comb.Bag The definition of insanity is quoting the same phrase again and again and not expect despair. "T" => 1 "h" => 3 "e" => 8 " " => 15 "d" => 4 "f" => 2 "i" => 10 "n" => 10 "t" => 6 "o" => 4 "s" => 5 "a" => 10 "y" => 1 "q" => 1 "u" => 1 "g" => 3 "m" => 1 "p" => 3 "r" => 2 "x" => 1 "c" => 1 "." => 1
J, 23 chars
(~.;"0+/@|:@=)/:~1!:1]1
Slightly different output format (line 2 is stdin):
(~.;"0+/@|:@=)/:~1!:1]1
Mississippi
┌─┬─┐
│M│1│
├─┼─┤
│i│4│
├─┼─┤
│p│2│
├─┼─┤
│s│4│
└─┴─┘
Windows Command Script - 72 Bytes
set/p.=
:a
set/a\%.:~,1%=\%.:~,1%+1
set.=%.:~1%
%.%goto:b
goto:a
:b
set\
Outputs:
\=15 (space)
\.=1
\a=10
\c=1
\d=4
\e=8
\f=2
\g=3
\h=3
\i=10
\m=1
\n=10
\o=4
\p=3
\q=1
\r=2
\s=5
\T=7
\u=1
\x=1
\y=1
PHP - 68 (or 39) bytes
<?foreach(count_chars(fgets(STDIN),1)as$k=>$v)echo chr($k)." : $v
";
Output for the example text:
: 15
. : 1
T : 1
a : 10
c : 1
d : 4
e : 8
f : 2
g : 3
h : 3
i : 10
m : 1
n : 10
o : 4
p : 3
q : 1
r : 2
s : 5
t : 6
u : 1
x : 1
y : 1
If the exact output is not required, this would work for 39 bytes:
<?print_r(count_chars(fgets(STDIN),1));
Sample output:
Array
(
[32] => 15
[46] => 1
[84] => 1
[97] => 10
[99] => 1
[100] => 4
[101] => 8
[102] => 2
[103] => 3
[104] => 3
[105] => 10
[109] => 1
[110] => 10
[111] => 4
[112] => 3
[113] => 1
[114] => 2
[115] => 5
[116] => 6
[117] => 1
[120] => 1
[121] => 1
)
where each numerical index refers the ordinal value of the character it represents.
I suspect very strongly that using an in-built function that does exactly what the problem states will soon be disallowed.
Powershell, 63
$a=@{};[char[]](read-host)|%{$a[$_]++};$a.Keys|%{"$_ :"+$a[$_]}

