# Display number of occurrences for every character in an input string

The code should take a string as input from keyboard:

The definition of insanity is quoting the same phrase again and again and not expect despair.


The output should be like this(not sorted in any particular order):

  :  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


All ASCII characters count unicode is not a requirement, spaces, quotes,etc and input should come from keyboard / not constants, attributes, output should be printed with new line after each character like in the above example, it should not be returned as string or dumped as hashmap/dictionary etc, so x : 1 and x: 1 are ok, but {'x':1,... and x:1 are not.

Q: Function or complete program taking stdin and writing stdout?
A: Code needs to be a program taking input using standard in and display the result via standard out.

# Scoreboard:

Shortest overall: 5 bytes

Shortest overall: 7 bytes

• All ascii characters as input? Or just printable? Or up to unicode? Will there be newlines? – Justin Jan 22 '14 at 8:21
• Can I create a function, or is a whole program necessary? Can I output all the ascii characters and print 0 as the number of occurrences? – Justin Jan 22 '14 at 8:21
• Is the output format strict, or it suffices to preserve the meaning? – John Dvorak Jan 22 '14 at 8:32
• Your edit did not address my question. – Justin Jan 22 '14 at 9:00
• You didn't say if the output needs to be sorted alphabetically. You didn't say if the separator needs to be " : " (note the two spaces after the :) or if other(shorter) seperators are fine. You didn't address the unicode/encoding issue. – CodesInChaos Jan 22 '14 at 18:11

# 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,:',:@j0:;#


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,:',:@j0:;#


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!~':;#


# 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... :)

## 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

• How do I put a single grave accent  in a code block? – Ben Reich Jan 24 '14 at 16:15

Scala, 64 chars

readLine.groupBy(y=>y).foreach(g=>println(g._1+" : "+g._2.size))


# 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.

• You could try to laminate maybe. – FUZxxl Feb 21 '15 at 23:38
• @FUZxxl Where? I have different types so I would have to format the numbers first. – randomra Feb 21 '15 at 23:41
• Indeed. Doesn't make it any shorter. I thought about something along the lines of ~.,&<"0#/.~ but that's too long. – FUZxxl Feb 21 '15 at 23:45

# JavaScript (Node.js), 64 bytes

e=>(d={},e.replace(/\S/g,e=>d[e]=d[e]+1||1),[Object.entries(d)])


Try it online!

# JavaScript (Node.js), 59 bytes

e=>(d={},[...e].map(e=>d[e]=d[e]+1||1),[Object.entries(d)])


Try it online!

• Hello, and welcome to PPCG! You seem to be used to our things :) Even though, don't hesitate to keep only one answer, or to tell us why you are keeping both. Happy golfing! – V. Courtois Aug 13 at 11:42

# Stax, 5 bytes

═#8¼K


Run and debug it

## 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])


# Smalltalk, 71

Stdin nextLine asBag valuesAndCountsDo:[:c :n|(c,' : ')print.n printNL]


# 05AB1E, 10 bytes (Non-competing)

ÙvyD¹s¢‚})


Try it online!

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]]

• 7 bytes: SÙDŠ¢‚ø 12 bytes: SÙDŠ¢‚ø„: ý» (provided that the result needs to be displayed according to the challenge specifications) – Kaldo Mar 29 '18 at 14:18
• @Kaldo 80% sure this answer was before we had zip even hah! Will update. – Magic Octopus Urn Mar 29 '18 at 14:38

# Swift 3: 122120 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

• I don't know the language, but are all those spaces in the source necessary? In most languages, it's possible to get some easy improvements to your score by removing whitespace (and when it isn't, it can help to give an explanation of why it's necessary). – user62131 Dec 2 '16 at 16:24
• whoops, in my previous edit I removed 2 bytes from the score but somehow i did not remove them from my code. thanks for pointing out – Devran Cosmo Uenal Dec 2 '16 at 16:30

# Tcl, 77 bytes

lmap c [split [gets stdin] ""] {dict inc D $c} dict ma k\ v$D {puts $k:\$v}


Try it online!

# Japt, 12 bytes

q
â ®+S+Uè¥Z


Try it online!

## 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

• 10 bytes – Shaggy Jun 22 '18 at 17:00

# 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>

# 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]);}


Try it online!

Takes input as command line argument.

# 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.


Try it online!

# SuperMarioLang, 449 bytes

     >++++)
>^====+  (+++<
>,[!^= (< +======"          *-<
"==#=  =" +      )      ======"
>%+>[!%+      )         >&[!
"====# +            )   "==#=====================
!        <>+++(-[!))+(%> [!!
#================#====="==##
>          (((++*)+*)&+)[!
"========================#
!)*-&)*-&)*-&)*-&.(((:)).(.(<
#==========================="


Try it online!

# Python 3, 46 bytes

i=input()
for c in{*i}:print(c,':',i.count(c))


Try it online!

D,g,@@#,€=b+": "$J D,f,@,qdA€gBcBJn  Try it online! 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


# 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> 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.


# Pip, 48 bytes

a:qFi32,128{b:0Fj,#a{a@jQ Ci?++bx}b?P Ci.":".bx}


I assume you meant printable ascii

Try it online!

# Julia 1.0, 53 bytes

s=readline()
Set(s).|>c->println(c,": ",sum(==(c),s))


Try it online!

# Stax (31 bytes)

âpWhuÉñ♫∩Ω╝YT>ⁿë╘Æ↨»╧óPÜ≤♪Ñû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

• Welcome! This does not meet the challenge's specifications. You need to support uppercase and symbols, and you should not show all characters. Your solution must work as shown in the example. It also gives the wrong answer, because it shows w:15, but the sample input has no w. – mbomb007 Aug 16 at 21:11

# Japt-R, 9 bytes

ü ®Î+S+Zl
`

Try it