26
\$\begingroup\$

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

\$\endgroup\$
16
  • 3
    \$\begingroup\$ All ascii characters as input? Or just printable? Or up to unicode? Will there be newlines? \$\endgroup\$
    – Justin
    Jan 22, 2014 at 8:21
  • 2
    \$\begingroup\$ 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? \$\endgroup\$
    – Justin
    Jan 22, 2014 at 8:21
  • 18
    \$\begingroup\$ Is the output format strict, or it suffices to preserve the meaning? \$\endgroup\$ Jan 22, 2014 at 8:32
  • \$\begingroup\$ Your edit did not address my question. \$\endgroup\$
    – Justin
    Jan 22, 2014 at 9:00
  • 7
    \$\begingroup\$ 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. \$\endgroup\$ Jan 22, 2014 at 18:11

66 Answers 66

2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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!`~':;#
\$\endgroup\$
2
\$\begingroup\$

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

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

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
\$\endgroup\$
1
  • \$\begingroup\$ How do I put a single grave accent ` in a code block? \$\endgroup\$
    – Ben Reich
    Jan 24, 2014 at 16:15
2
\$\begingroup\$

Scala, 64 chars

readLine.groupBy(y=>y).foreach(g=>println(g._1+" : "+g._2.size))
\$\endgroup\$
2
\$\begingroup\$

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.

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

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!

\$\endgroup\$
2
  • \$\begingroup\$ It should be mentioned that a needs to be initialized with zeros. By definition variables of “unmanaged” data types are uninitialized. You make use of the zero-initialization as common in modern multi-user operating systems, which prevents data leaks between users/processes. \$\endgroup\$ Mar 5, 2023 at 15:56
  • \$\begingroup\$ This is code golf, where the normal rules of programming go out the window, in the quest to find the golfiest solution. Compiler warnings and whatnot do not matter :) \$\endgroup\$
    – roblogic
    Mar 6, 2023 at 18:03
2
\$\begingroup\$

SuperMarioLang, 449 bytes

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

Try it online!

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

Stax, 5 bytes

═#8¼K

Run and debug it

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

Python, 46 bytes

s=input()
for c in{*s}:print(c,":",s.count(c))

Attempt it Online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Hi there, welcome to code golf! I've just added a link to ATO, a site where you can run programs from the browser. Nice first answer! \$\endgroup\$
    – lyxal
    Mar 5, 2023 at 12:53
2
\$\begingroup\$

Pip -S, 16 bytes

{[a':aNy]}MUQ Yq

Attempt This Online!

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

Attempt This Online!

\$\endgroup\$
1
\$\begingroup\$

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])
\$\endgroup\$
1
\$\begingroup\$

Smalltalk, 71

Stdin nextLine asBag valuesAndCountsDo:[:c :n|(c,' : ')print.n printNL]
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ 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). \$\endgroup\$
    – user62131
    Dec 2, 2016 at 16:24
  • \$\begingroup\$ 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 \$\endgroup\$ Dec 2, 2016 at 16:30
1
\$\begingroup\$

Tcl, 77 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ 10 bytes \$\endgroup\$
    – Shaggy
    Jun 22, 2018 at 17:00
1
\$\begingroup\$

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.

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

Python 3, 46 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Add++, 35 bytes

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
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 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! \$\endgroup\$ Aug 13, 2019 at 11:42
1
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Julia 1.0, 53 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – mbomb007
    Aug 16, 2019 at 21:11
1
\$\begingroup\$

Japt -R, 9 bytes

ü ®Î+S+Zl

Try it

\$\endgroup\$
1
\$\begingroup\$

Vyxal, 11 bytes

Ċ⟑`%: %`$%,

Try it Online!

\$\endgroup\$
1
\$\begingroup\$

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 as c.
  • q,LEN(A1)-LEN(SUBSTITUTE(A1,c,)) stores a list q of how much shorter the input would be if you removed each ASCII character in turn.
  • FILTER(c&": "&q,q>0) combines c and q into the desired output format and then filters the list to just show those that actually appear in the input.

Screenshot

\$\endgroup\$
1
\$\begingroup\$

PowerShell Core, 42 bytes

$input|% t*y|group|%{$_.Name+":"+$_.Count}

Try it online!

Converts the input into an array of characters
Group them and builds a string like <char>:<count> for each of them

\$\endgroup\$
1
\$\begingroup\$

Arturo, 41 bytes

loop tally input""[x,y]->print~"|x|: |y|"

enter image description here

\$\endgroup\$
1
\$\begingroup\$

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)

Try it online!

\$\endgroup\$

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.