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
    Commented 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
    Commented Jan 22, 2014 at 8:21
  • 18
    \$\begingroup\$ Is the output format strict, or it suffices to preserve the meaning? \$\endgroup\$ Commented Jan 22, 2014 at 8:32
  • \$\begingroup\$ Your edit did not address my question. \$\endgroup\$
    – Justin
    Commented 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\$ Commented Jan 22, 2014 at 18:11

66 Answers 66

15
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ $argv[1] instead of fgets(STDIN) saves 4 bytes. \$\endgroup\$
    – Titus
    Commented Dec 2, 2016 at 16:56
14
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ Pretty incredible. \$\endgroup\$ Commented Jan 22, 2014 at 23:39
  • \$\begingroup\$ the : in =: is superfluous; k)#:'=0:0 works fine (7 chars). (bonus for knowing about 0:0, i had no idea!) \$\endgroup\$ Commented Jan 23, 2014 at 4:59
  • \$\begingroup\$ A detailed explanation would be really cool :) \$\endgroup\$
    – Timwi
    Commented Jan 24, 2014 at 20:12
  • \$\begingroup\$ q translation is easier to understand - count each group read0 0 \$\endgroup\$
    – skeevey
    Commented Jan 25, 2014 at 16:15
13
\$\begingroup\$

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

\$\endgroup\$
7
  • 2
    \$\begingroup\$ For 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. \$\endgroup\$
    – FireFly
    Commented Jan 22, 2014 at 8:59
  • \$\begingroup\$ Oh thanks you! Updated. I should not forget grep -o; it is a useful one. \$\endgroup\$ Commented Jan 22, 2014 at 9:08
  • 2
    \$\begingroup\$ fold -1 does the same thing as grep -o . \$\endgroup\$
    – user15244
    Commented Jan 22, 2014 at 15:28
  • \$\begingroup\$ Awesome :) Learning new tricks! \$\endgroup\$ Commented Jan 22, 2014 at 15:38
  • 1
    \$\begingroup\$ ptx -S. does the same trick. \$\endgroup\$ Commented Jan 22, 2014 at 23:36
7
\$\begingroup\$

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

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}
\$\endgroup\$
14
  • 1
    \$\begingroup\$ 63 chars a=gets.strip;a.split('').uniq.each{|x|puts"#{x} : #{a.count(x)}"} \$\endgroup\$
    – Siva
    Commented Jan 22, 2014 at 12:22
  • \$\begingroup\$ Why to strip()? The question says, “all characters count”. \$\endgroup\$
    – manatwork
    Commented Jan 22, 2014 at 12:35
  • \$\begingroup\$ Well, gets will return \n even if you dont intend to \$\endgroup\$
    – Siva
    Commented Jan 22, 2014 at 12:37
  • \$\begingroup\$ Nope. Only returns \n if it was really passed. Passing it is a side-effect of using here-string. pastebin.com/gCrgk9m1 \$\endgroup\$
    – manatwork
    Commented Jan 22, 2014 at 12:42
  • 1
    \$\begingroup\$ Using $_ and ditching a is still sound though. And c+"... instead of "#{c}... \$\endgroup\$
    – daniero
    Commented Jan 22, 2014 at 14:57
7
\$\begingroup\$

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))
\$\endgroup\$
2
  • \$\begingroup\$ The 45 char version prints characters more than once. \$\endgroup\$
    – ugoren
    Commented Jan 22, 2014 at 14:40
  • \$\begingroup\$ @evuez I just fixed your 45 char version. But, you removed it so I have submitted it once again. Have a look \$\endgroup\$
    – Wasi
    Commented Jan 22, 2014 at 15:21
5
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Semi-serious question -- what's it like maintaining legacy APL code? \$\endgroup\$ Commented Jan 25, 2014 at 2:41
  • \$\begingroup\$ @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. \$\endgroup\$
    – marinus
    Commented Jan 25, 2014 at 21:44
5
\$\begingroup\$

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 
\$\endgroup\$
2
  • \$\begingroup\$ Good idea! But the question says the code must print the result. Your code just returns the result. I suppose you need cat. \$\endgroup\$ Commented Jan 24, 2014 at 16:22
  • \$\begingroup\$ @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. \$\endgroup\$
    – plannapus
    Commented Jan 24, 2014 at 16:35
5
\$\begingroup\$

Perl 5, 54 characters

map{$h{$_}++}split//,<>;print"$_ : $h{$_}\n"for keys%h
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Very nice solution, easy to read. That would need to be sort keys%h, though. \$\endgroup\$
    – primo
    Commented Jan 22, 2014 at 11:49
  • 1
    \$\begingroup\$ Hey @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//,<>; \$\endgroup\$ Commented Jan 22, 2014 at 15:24
  • 1
    \$\begingroup\$ @DomHastings or $h{$_}++for<>=~/./g, which I think might be optimal. Literal newline instead of \n as well. \$\endgroup\$
    – primo
    Commented Jan 22, 2014 at 15:33
  • \$\begingroup\$ Ah nice, even better! Yes, I forgot to mention the literal newline, that's become my new favourite -1 byte! \$\endgroup\$ Commented Jan 22, 2014 at 15:52
5
\$\begingroup\$

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.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ map 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 \$\endgroup\$
    – imma
    Commented Jan 22, 2014 at 12:47
  • 1
    \$\begingroup\$ you 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 \$\endgroup\$
    – eithed
    Commented Jan 22, 2014 at 13:35
  • 1
    \$\begingroup\$ nice :-) 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 \$\endgroup\$
    – imma
    Commented Jan 22, 2014 at 16:04
  • \$\begingroup\$ 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]) \$\endgroup\$
    – imma
    Commented Jan 22, 2014 at 16:25
  • 1
    \$\begingroup\$ @VisioN only if the primitives are overloaded - for in indeed gives you functions in SO, but not in empty tab ;) \$\endgroup\$
    – eithed
    Commented Jan 22, 2014 at 18:09
5
\$\begingroup\$

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}
\$\endgroup\$
2
  • \$\begingroup\$ Forgot to remove the brackets after print in the second one, that makes it 41 \$\endgroup\$ Commented Jan 23, 2014 at 8:30
  • \$\begingroup\$ 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} \$\endgroup\$
    – evuez
    Commented Jan 23, 2014 at 13:48
5
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ nice improvement! why don't you remove the sorted()? \$\endgroup\$
    – evuez
    Commented Jan 22, 2014 at 15:21
  • 1
    \$\begingroup\$ right! 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)) \$\endgroup\$
    – evuez
    Commented Jan 22, 2014 at 15:38
  • \$\begingroup\$ @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 \$\endgroup\$
    – Wasi
    Commented Jan 22, 2014 at 15:50
  • \$\begingroup\$ Wouldn't be fair, I hadn't thought about set()! ;) \$\endgroup\$
    – evuez
    Commented Jan 22, 2014 at 16:09
3
\$\begingroup\$

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)

\$\endgroup\$
3
  • \$\begingroup\$ Looks like the : is unfortunately required in the output (you can't delete this answer). \$\endgroup\$ Commented Mar 29, 2018 at 19:49
  • \$\begingroup\$ @EriktheOutgolfer How do you deduce that? Clearly OP found this answer acceptable, in accordance with an old comment. \$\endgroup\$
    – Adám
    Commented Mar 29, 2018 at 20:42
  • \$\begingroup\$ Another reason for spec to be in the question itself... \$\endgroup\$ Commented Mar 29, 2018 at 20:48
3
\$\begingroup\$

Haskell, 93

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

PowerShell (49)

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

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])));}}
\$\endgroup\$
6
  • \$\begingroup\$ 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)));}} \$\endgroup\$
    – Spongman
    Commented Jan 23, 2014 at 19:15
  • \$\begingroup\$ 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());}} \$\endgroup\$
    – Spongman
    Commented Jan 23, 2014 at 19:21
  • \$\begingroup\$ 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());}} \$\endgroup\$
    – Spongman
    Commented Jan 24, 2014 at 5:57
  • \$\begingroup\$ Wow. Quick or coincidence ? You replied just a second after I updated my answer :D Just noticed that sorting wasn't explicitly mentioned! \$\endgroup\$
    – gideon
    Commented Jan 24, 2014 at 5:58
  • 3
    \$\begingroup\$ 148: namespace System{using Linq;class F{static void Main(){foreach(var g in Console.ReadLine().GroupBy(c=>c))Console.WriteLine(g.Key+" : "+g.Count());}} \$\endgroup\$
    – Timwi
    Commented Jan 24, 2014 at 20:02
3
\$\begingroup\$

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

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)
\$\endgroup\$
2
  • \$\begingroup\$ 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") \$\endgroup\$
    – goric
    Commented Jan 25, 2014 at 1:02
  • \$\begingroup\$ In fact, why even sort in the first place? let f s=Seq.countBy id s|>Seq.iter(printfn"%A") \$\endgroup\$
    – goric
    Commented Jan 25, 2014 at 1:10
3
\$\begingroup\$

Mathematica, 34 29 bytes

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

Grid@Tally@Characters@Input[]
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ 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" \$\endgroup\$
    – zeppelin
    Commented Dec 2, 2016 at 15:13
  • \$\begingroup\$ @zeppelin a little googling confimrs what you've said \$\endgroup\$ Commented Dec 2, 2016 at 15:35
  • 1
    \$\begingroup\$ Your ptx -S. solution doesn't work on my machine or TIO. However this works, for 20 bytes: fold -1|sort|uniq -c \$\endgroup\$
    – roblogic
    Commented Mar 6, 2023 at 18:26
3
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ 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));}}} \$\endgroup\$
    – Poke
    Commented Dec 2, 2016 at 14:54
  • 2
    \$\begingroup\$ m.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. \$\endgroup\$ Commented Mar 2, 2018 at 8:40
3
\$\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\$
2
\$\begingroup\$

Powershell, 63

$a=@{};[char[]](read-host)|%{$a[$_]++};$a.Keys|%{"$_ :"+$a[$_]}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Each 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 \$\endgroup\$
    – goric
    Commented Jan 24, 2014 at 21:41
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Nice! It does fold case though, but it's always amazing to see actual cleverness in batch file programming. \$\endgroup\$ Commented Jan 24, 2014 at 16:40
2
\$\begingroup\$

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│
└─┴─┘
\$\endgroup\$
2
\$\begingroup\$

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

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ The question asks for input from the keyboard, so the first line should be string str = Console.ReadLine();. But this is 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. \$\endgroup\$ Commented Jan 22, 2014 at 12:15
  • \$\begingroup\$ You're right, I edited my answer. \$\endgroup\$
    – Aviv
    Commented Jan 22, 2014 at 13:13
2
\$\begingroup\$

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());
\$\endgroup\$
2
  • \$\begingroup\$ Won't compile, need to add about 50 chars for usings/namespace/class/method definitions. \$\endgroup\$ Commented Jan 22, 2014 at 19:45
  • \$\begingroup\$ Oh, didn't know that was mandatory, I'm sorry. \$\endgroup\$
    – Abbas
    Commented Jan 22, 2014 at 20:12

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.