Display number of occurrences for every character in an input string

21

4

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

Eduard Florinescu

Posted 2014-01-22T08:07:00.530

Reputation: 1 863

3All ascii characters as input? Or just printable? Or up to unicode? Will there be newlines? – Justin – 2014-01-22T08:21:35.777

2Can 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 – 2014-01-22T08:21:57.683

16Is the output format strict, or it suffices to preserve the meaning? – John Dvorak – 2014-01-22T08:32:55.103

Your edit did not address my question. – Justin – 2014-01-22T09:00:16.720

5You 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 – 2014-01-22T18:11:50.820

what kind of sort order is that? – Spongman – 2014-01-23T18:57:55.147

@Spongman The missing one type – Eduard Florinescu – 2014-01-23T23:41:47.953

Function or complete program taking stdin and writing stdout? – MtnViewMark – 2014-01-24T15:25:46.197

The "shortest overall" does not follow the required output. Is that okay? – microbian – 2014-01-24T15:51:10.527

@microbian I see that as a soft requirement :) – Eduard Florinescu – 2014-01-24T15:52:40.517

@Eduard Florinescu, yeah, but the trouble is that your output IS sorted - losely as if it were read from a binary heap. yet you do not specify if that is a requirement. you say "The output should be" which implies that the order should be maintained. – Spongman – 2014-01-24T18:51:36.027

@Spongman I used a dictionary for that, that's why, I will edit the question. – Eduard Florinescu – 2014-01-24T19:08:44.773

@EduardFlorinescu What about JavaScript? There is no standard input. You could say that the console is standard output. – Toothbrush – 2014-01-24T19:12:15.400

@toothbrush prompt()? readline for nodejs – Eduard Florinescu – 2014-01-24T19:14:35.463

@toothbrush nodejs: http://stackoverflow.com/questions/5006821/nodejs-how-to-read-keystrokes-from-stdin

– Eduard Florinescu – 2014-01-24T19:21:38.770

@EduardFlorinescu OK, thank you. I was thinking about in the browser. Is it OK to pass the string in a variable, then? – Toothbrush – 2014-01-24T19:35:09.243

Answers

2

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.

,∘≢⌸⍞

Try it online!

 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)

Adám

Posted 2014-01-22T08:07:00.530

Reputation: 37 779

Looks like the : is unfortunately required in the output (you can't delete this answer). – Erik the Outgolfer – 2018-03-29T19:49:21.593

@EriktheOutgolfer How do you deduce that? Clearly OP found this answer acceptable, in accordance with an old comment.

– Adám – 2018-03-29T20:42:56.510

Another reason for spec to be in the question itself... – Erik the Outgolfer – 2018-03-29T20:48:33.490

15

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.

primo

Posted 2014-01-22T08:07:00.530

Reputation: 30 891

$argv[1] instead of fgets(STDIN) saves 4 bytes. – Titus – 2016-12-02T16:56:10.123

14

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

skeevey

Posted 2014-01-22T08:07:00.530

Reputation: 4 139

Pretty incredible. – Pureferret – 2014-01-22T23:39:36.407

the : in =: is superfluous; k)#:'=0:0 works fine (7 chars). (bonus for knowing about 0:0, i had no idea!) – Aaron Davies – 2014-01-23T04:59:38.337

A detailed explanation would be really cool :) – Timwi – 2014-01-24T20:12:36.860

q translation is easier to understand - count each group read0 0 – skeevey – 2014-01-25T16:15:40.270

13

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

joeytwiddle

Posted 2014-01-22T08:07:00.530

Reputation: 601

2For sed you can use & for "whole match" instead of \0, though grep -o . is slightly shorter yet. It's worth mentioning that the output of uniq -c differs slightly from the one given in the question. – FireFly – 2014-01-22T08:59:57.200

Oh thanks you! Updated. I should not forget grep -o; it is a useful one. – joeytwiddle – 2014-01-22T09:08:16.940

2fold -1 does the same thing as grep -o . – None – 2014-01-22T15:28:20.237

Awesome :) Learning new tricks! – joeytwiddle – 2014-01-22T15:38:24.030

1ptx -S. does the same trick. – Pureferret – 2014-01-22T23:36:09.550

I like it! However, it doesn't comply with the "output should be printed with new line after each character" requirement. – Brian Minton – 2014-01-24T16:24:59.190

actually, I just misread the rule. :-) – Brian Minton – 2014-01-31T16:05:07.540

7

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

evuez

Posted 2014-01-22T08:07:00.530

Reputation: 383

The 45 char version prints characters more than once. – ugoren – 2014-01-22T14:40:40.433

Right... Thanks for noticing! – evuez – 2014-01-22T14:43:29.000

@evuez I just fixed your 45 char version. But, you removed it so I have submitted it once again. Have a look

– Wasi – 2014-01-22T15:21:23.507

7

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}

manatwork

Posted 2014-01-22T08:07:00.530

Reputation: 17 865

163 chars a=gets.strip;a.split('').uniq.each{|x|puts"#{x} : #{a.count(x)}"} – Siva – 2014-01-22T12:22:22.380

Why to strip()? The question says, “all characters count”. – manatwork – 2014-01-22T12:35:38.513

Well, gets will return \n even if you dont intend to – Siva – 2014-01-22T12:37:32.207

Nope. Only returns \n if it was really passed. Passing it is a side-effect of using here-string. http://pastebin.com/gCrgk9m1

– manatwork – 2014-01-22T12:42:16.817

Then it becomes 57 chars – Siva – 2014-01-22T12:44:32.857

57 -> 49 characters: puts gets.chars.uniq.map{|c|c+" : #{$_.count c}"} if you don't mind newline being counted – daniero – 2014-01-22T14:52:24.850

@daniero, is that ruby 2++? “NoMethodError: undefined method `uniq' for #<Enumerator: "\n":chars>” – manatwork – 2014-01-22T14:54:53.157

Oh, probably ;) – daniero – 2014-01-22T14:55:56.957

1Using $_ and ditching a is still sound though. And c+"... instead of "#{c}... – daniero – 2014-01-22T14:57:46.480

Looking at 2.1.0 documentation, neither Enumerator nor Enumerable has such method…

– manatwork – 2014-01-22T15:01:51.163

Yes, but chars now returns an array.

– daniero – 2014-01-22T15:03:37.013

Oh. Seems I really have to read a good amount of changelogs. Thank you, @daniero. – manatwork – 2014-01-22T15:07:40.510

why require pp? Couldn't you use p and save a character? – Shelvacu – 2014-01-23T04:55:26.287

@shelvacu, I tried to keep at least partially the vertical listing format. Most of the other answers are doing something similar. – manatwork – 2014-01-23T09:34:06.020

6

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

Ayiko

Posted 2014-01-22T08:07:00.530

Reputation: 519

5

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

marinus

Posted 2014-01-22T08:07:00.530

Reputation: 30 224

Semi-serious question -- what's it like maintaining legacy APL code? – Michael Stern – 2014-01-25T02:41:13.933

@MichaelStern: No idea, I've never had to do that. But I'd guess it's no worse than maintaining other legacy code. APL is actually quite easy to read once you're used to it. – marinus – 2014-01-25T21:44:22.043

5

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 

plannapus

Posted 2014-01-22T08:07:00.530

Reputation: 8 610

Good idea! But the question says the code must print the result. Your code just returns the result. I suppose you need cat. – Sven Hohenstein – 2014-01-24T16:22:02.433

@SvenHohenstein well it wasn't specified when i answered (i answered before revision 4 of the question)... but as a matter of fact cat will only return the values not the value names (i. e. the characters). So it would need a more complex solution. – plannapus – 2014-01-24T16:35:51.377

5

Perl 5, 54 characters

map{$h{$_}++}split//,<>;print"$_ : $h{$_}\n"for keys%h

protist

Posted 2014-01-22T08:07:00.530

Reputation: 570

1Very nice solution, easy to read. That would need to be sort keys%h, though. – primo – 2014-01-22T11:49:38.053

1Hey @protist, looks good! I agree with @primo though! You can however save two chars using $_=<>;s/./$h{$_}++/eg; or map{$h{$_}++}<>=~/./g; instead of map{$h{$_}++}split//,<>; – Dom Hastings – 2014-01-22T15:24:42.987

1@DomHastings or $h{$_}++for<>=~/./g, which I think might be optimal. Literal newline instead of \n as well. – primo – 2014-01-22T15:33:47.353

Ah nice, even better! Yes, I forgot to mention the literal newline, that's become my new favourite -1 byte! – Dom Hastings – 2014-01-22T15:52:25.390

5

JavaScript

  1. 66 53 bytes:

    prompt(a={}).replace(/./g,function(c){a[c]=-~a[c]}),a
    
  2. 69 56 bytes:

    b=prompt(a={});for(i=b.length;i--;){a[b[i]]=-~a[b[i]]};a
    
  3. 78 65 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.

VisioN

Posted 2014-01-22T08:07:00.530

Reputation: 4 490

1map instead of a loop help a little also (a[b[i]]||0)+1 can be reduced to -~a[b[i]] & console.log can probably go, just returning the last value, giving prompt(a={}).split("").map(function(c){a[c]=-~a[c]});a – imma – 2014-01-22T12:47:45.050

1you can change for into for in - testing in empty tab produces the same results. Also, the last ; is not needed, thus: b=prompt(a={});for(i in b){a[b[i]]=-~a[b[i]]}a – eithed – 2014-01-22T13:35:38.870

1nice :-) stick the b=... into the for & swop the for{}'s for a ; for another 2 bytes off : for(i in b=prompt(a={}))a[b[i]]=-~a[b[i]];a – imma – 2014-01-22T16:04:46.250

although they may want exact text output :-/ which puts it/me back up by 36 (to 79) bytes : for(i in b=prompt(a={}))a[b[i]]=-~a[b[i]];for(n in a)console.log(n+" : "+a[n]) – imma – 2014-01-22T16:25:41.557

@imma for .. in is not the best choice for arrays and strings: it will grab own properties of the objects behind them. Normal loop is the way to go here IMO. – VisioN – 2014-01-22T16:28:19.530

1@VisioN only if the primitives are overloaded - for in indeed gives you functions in SO, but not in empty tab ;) – eithed – 2014-01-22T18:09:20.477

5

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}

ToonAlfrink

Posted 2014-01-22T08:07:00.530

Reputation: 1 122

Forgot to remove the brackets after print in the second one, that makes it 41 – ToonAlfrink – 2014-01-23T08:30:36.117

You can go down to 52 chars with your first version: for l in set(s):print l,":",s.count(l). For the second one, removing unnecessary spaces makes you win 2 chars: print{l:s.count(l)for l in s} – evuez – 2014-01-23T13:48:59.427

5

Mathematica, 61 bytes

Map[{#[[1]], Length@#} &, Gather@Characters[Input[]]] // TableForm

It then pops up this dialog box,

input

and for the sample sentence, produces as output

output

Michael Stern

Posted 2014-01-22T08:07:00.530

Reputation: 3 029

4

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

Wasi

Posted 2014-01-22T08:07:00.530

Reputation: 1 682

nice improvement! why don't you remove the sorted()? – evuez – 2014-01-22T15:21:07.157

1right! anyway, if you don't use a list comprehension, it's 1 char less: for i in sorted(set(t)):print(i,':',t.count(i)) – evuez – 2014-01-22T15:38:15.373

@evuez Thanks, I was supposed to add it as a comment in your code. If you like you can add it again in your solution(I will happily delete this one) :D – Wasi – 2014-01-22T15:50:56.433

Wouldn't be fair, I hadn't thought about set()! ;) – evuez – 2014-01-22T16:09:05.430

4

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.

Toothbrush

Posted 2014-01-22T08:07:00.530

Reputation: 3 197

3

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)

Rik

Posted 2014-01-22T08:07:00.530

Reputation: 781

You can drop a character by switching away from the piped syntax for a few of the function calls: let f s=Seq.countBy id (Seq.sort s)|>Seq.iter(printfn"%A") – goric – 2014-01-25T01:02:45.993

In fact, why even sort in the first place? let f s=Seq.countBy id s|>Seq.iter(printfn"%A") – goric – 2014-01-25T01:10:46.250

3

Haskell, 93

import Data.List
main=getLine>>=mapM(\s->putStrLn$[head s]++" : "++show(length s)).group.sort

Vektorweg

Posted 2014-01-22T08:07:00.530

Reputation: 301

3

PowerShell (49)

[char[]](read-host)|group|%{$_.Name+":"+$_.Count}

microbian

Posted 2014-01-22T08:07:00.530

Reputation: 2 297

3

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

Pureferret

Posted 2014-01-22T08:07:00.530

Reputation: 960

just out of curiosity, do you really need |sort| here, AFAIK ptx will already produce a sorted list of chars which you can feed directly to "uniq -c" – zeppelin – 2016-12-02T15:13:56.960

@zeppelin a little googling confimrs what you've said – Pureferret – 2016-12-02T15:35:05.193

3

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

gideon

Posted 2014-01-22T08:07:00.530

Reputation: 131

doesn't compile. this one does: 178 chars. using System.Linq;using C=System.Console;class F{static void Main(){C.WriteLine(string.Join("\n",C.ReadLine().GroupBy(c=>c).Select(g=>g.Key+" : "+g.Count()).OrderBy(s=>s)));}} – Spongman – 2014-01-23T19:15:59.810

168: using C=System.Console;using System.Linq;class F{static void Main(){foreach(var g in C.ReadLine().GroupBy(c=>c).OrderBy(g=>g.Key))C.WriteLine(g.Key+" : "+g.Count());}} – Spongman – 2014-01-23T19:21:39.363

apparently sorting is unneccesary, 150: using C=System.Console;using System.Linq;class F{static void Main(){foreach(var g in C.ReadLine().GroupBy(c=>c))C.WriteLine(g.Key+" : "+g.Count());}} – Spongman – 2014-01-24T05:57:12.173

Wow. Quick or coincidence ? You replied just a second after I updated my answer :D Just noticed that sorting wasn't explicitly mentioned! – gideon – 2014-01-24T05:58:59.723

3148: namespace System{using Linq;class F{static void Main(){foreach(var g in Console.ReadLine().GroupBy(c=>c))Console.WriteLine(g.Key+" : "+g.Count());}} – Timwi – 2014-01-24T20:02:32.793

wow @Timwi that was neat! – gideon – 2014-01-25T05:56:35.130

3

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
丟

Timwi

Posted 2014-01-22T08:07:00.530

Reputation: 12 158

3

Mathematica, 34 29 bytes

Not sure why the other Mathematica answer is so complicated... ;)

Grid@Tally@Characters@Input[]

Martin Ender

Posted 2014-01-22T08:07:00.530

Reputation: 184 808

3

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:

Try it here.

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

Kevin Cruijssen

Posted 2014-01-22T08:07:00.530

Reputation: 67 575

249 bytes import java.util.*;class I{public static void main(String[]a){Map m=new HashMap();for(char c:new Scanner(System.in).nextLine().toCharArray()){m.put(c,m.get(c)!=null?(int)m.get(c)+1:1);}for(Object e:m.keySet()){System.out.println(e+": "+m.get(e));}}} – Poke – 2016-12-02T14:54:31.323

2m.compute(c,(k,v)->v!=null?(int)v+1:1); instead of m.put(c,m.get(c‌​)!=null?(int)m.get(c‌​)+1:1); to save 3 bytes. – Olivier Grégoire – 2018-03-02T08:40:05.590

2

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!

Rajan Kumar

Posted 2014-01-22T08:07:00.530

Reputation: 71

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 – 2019-08-13T11:42:03.017

2

recursive

Posted 2014-01-22T08:07:00.530

Reputation: 8 616

2

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

Justin

Posted 2014-01-22T08:07:00.530

Reputation: 19 757

2

Powershell, 63

$a=@{};[char[]](read-host)|%{$a[$_]++};$a.Keys|%{"$_ :"+$a[$_]}

Danko Durbić

Posted 2014-01-22T08:07:00.530

Reputation: 10 241

2Each key in a hash can be accessed as a property on that hash, so you can shave off two characters by replacing each instance of $a[$_] with $a.$_ . See help about_hash_tables – goric – 2014-01-24T21:41:22.977

2

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

Robert Sørlie

Posted 2014-01-22T08:07:00.530

Reputation: 1 036

Nice! It does fold case though, but it's always amazing to see actual cleverness in batch file programming. – Brian Minton – 2014-01-24T16:40:15.127

2

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│
└─┴─┘

FireFly

Posted 2014-01-22T08:07:00.530

Reputation: 7 107

2

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

Aviv

Posted 2014-01-22T08:07:00.530

Reputation: 21

1The question asks for input from the keyboard, so the first line should be string str = Console.ReadLine();. But this is [tag:code-golf] so it should actually be var str=Console.ReadLine();. The other comments I would like to make have to be put on hold until OP improves the question. – Peter Taylor – 2014-01-22T12:15:41.350

You're right, I edited my answer. – Aviv – 2014-01-22T13:13:58.800

2

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

Gareth

Posted 2014-01-22T08:07:00.530

Reputation: 11 678

2

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());

Abbas

Posted 2014-01-22T08:07:00.530

Reputation: 349

Won't compile, need to add about 50 chars for usings/namespace/class/method definitions. – Pierre-Luc Pineault – 2014-01-22T19:45:57.353

Oh, didn't know that was mandatory, I'm sorry. – Abbas – 2014-01-22T20:12:07.937

2

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

Paul Bissex

Posted 2014-01-22T08:07:00.530

Reputation: 121

2

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

Ben Reich

Posted 2014-01-22T08:07:00.530

Reputation: 1 577

How do I put a single grave accent ` in a code block? – Ben Reich – 2014-01-24T16:15:15.663

2

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

cormullion

Posted 2014-01-22T08:07:00.530

Reputation: 569

2

Scala, 64 chars

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

Dan G

Posted 2014-01-22T08:07:00.530

Reputation: 191

2

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.

randomra

Posted 2014-01-22T08:07:00.530

Reputation: 19 909

You could try to laminate maybe. – FUZxxl – 2015-02-21T23:38:06.443

@FUZxxl Where? I have different types so I would have to format the numbers first. – randomra – 2015-02-21T23:41:55.327

Indeed. Doesn't make it any shorter. I thought about something along the lines of ~.,&<"0#/.~ but that's too long. – FUZxxl – 2015-02-21T23:45:38.473

1

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

Devran Cosmo Uenal

Posted 2014-01-22T08:07:00.530

Reputation: 111

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). – None – 2016-12-02T16:24:31.180

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 – 2016-12-02T16:30:09.197

1

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

Magic Octopus Urn

Posted 2014-01-22T08:07:00.530

Reputation: 19 422

17 bytes: SÙDŠ¢‚ø 12 bytes: SÙDŠ¢‚ø„: ý» (provided that the result needs to be displayed according to the challenge specifications) – Kaldo – 2018-03-29T14:18:27.917

1@Kaldo 80% sure this answer was before we had zip even hah! Will update. – Magic Octopus Urn – 2018-03-29T14:38:09.230

1

Tcl, 77 bytes

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

Try it online!

sergiol

Posted 2014-01-22T08:07:00.530

Reputation: 3 055

1

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>

Shaggy

Posted 2014-01-22T08:07:00.530

Reputation: 24 623

1

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.

vazt

Posted 2014-01-22T08:07:00.530

Reputation: 311

1

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

Oliver

Posted 2014-01-22T08:07:00.530

Reputation: 7 160

10 bytes – Shaggy – 2018-06-22T17:00:10.833

1

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!

AlexRacer

Posted 2014-01-22T08:07:00.530

Reputation: 979

1

SuperMarioLang, 449 bytes

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

Try it online!

Charlie

Posted 2014-01-22T08:07:00.530

Reputation: 11 448

1

Python 3, 46 bytes

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

Try it online!

movatica

Posted 2014-01-22T08:07:00.530

Reputation: 635

1

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

caird coinheringaahing

Posted 2014-01-22T08:07:00.530

Reputation: 13 702

1

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.

Dr Y Wit

Posted 2014-01-22T08:07:00.530

Reputation: 511

1

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!

Kenneth Taylor

Posted 2014-01-22T08:07:00.530

Reputation: 183

1

Julia 1.0, 53 bytes

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

Try it online!

user3263164

Posted 2014-01-22T08:07:00.530

Reputation: 381

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

user89655

Posted 2014-01-22T08:07:00.530

Reputation: 31

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 – 2019-08-16T21:11:35.953

1

Japt -R, 9 bytes

ü ®Î+S+Zl

Try it

Shaggy

Posted 2014-01-22T08:07:00.530

Reputation: 24 623

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

wolfhammer

Posted 2014-01-22T08:07:00.530

Reputation: 1 219

1

Smalltalk, 71

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

blabla999

Posted 2014-01-22T08:07:00.530

Reputation: 1 869