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

54 Answers 54

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\$
  • \$\begingroup\$ How do I put a single grave accent ` in a code block? \$\endgroup\$ – Ben Reich Jan 24 '14 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\$
  • \$\begingroup\$ You could try to laminate maybe. \$\endgroup\$ – FUZxxl Feb 21 '15 at 23:38
  • \$\begingroup\$ @FUZxxl Where? I have different types so I would have to format the numbers first. \$\endgroup\$ – randomra Feb 21 '15 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 '15 at 23:45
2
\$\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\$
  • \$\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\$ – V. Courtois Aug 13 at 11:42
2
\$\begingroup\$

Stax, 5 bytes

═#8¼K

Run and debug it

\$\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\$

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]]
\$\endgroup\$
  • 1
    \$\begingroup\$ 7 bytes: SÙDŠ¢‚ø 12 bytes: SÙDŠ¢‚ø„: ý» (provided that the result needs to be displayed according to the challenge specifications) \$\endgroup\$ – Kaldo Mar 29 '18 at 14:18
  • 1
    \$\begingroup\$ @Kaldo 80% sure this answer was before we had zip even hah! Will update. \$\endgroup\$ – Magic Octopus Urn Mar 29 '18 at 14:38
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\$
  • \$\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 '16 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\$ – Devran Cosmo Uenal Dec 2 '16 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\$
  • \$\begingroup\$ 10 bytes \$\endgroup\$ – Shaggy Jun 22 '18 at 17:00
1
\$\begingroup\$

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>

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

SuperMarioLang, 449 bytes

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

Try it online!

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

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\$
  • \$\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 at 21:11
1
\$\begingroup\$

Japt -R, 9 bytes

ü ®Î+S+Zl

Try it

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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