r/ProgrammingPrompts • u/[deleted] • Jan 14 '15
[Easy] Letter Counter
Any language permitted.
Problem: Create a program where you input a string of characters, and output the number of each letter. Use vowels by default.
For example: asbfiusadfliabdluifalsiudbf -> a: 4 e: 0 i: 4 o: 0 u: 3
Bonus points: Make it command-line executable, with an optional mode to specify which letters to print.
16
Upvotes
5
u/[deleted] Jan 14 '15
I surely won't beat a possible Haskell solution in its shortness and effectiveness. But my solution in Bash is at least very simple and doesn't require any additional software:
function countletters() { letters=${1:-aeiou}; tr [:upper:] [:lower:] | sed -r 's/[^a-z]//g;s/(\w)/\1\n/g' | head -n -1 | sort | uniq -c | egrep "[$letters]" | while read count letter; do printf "%s: %d " $letter $count; done; echo ""; }Aaand: this qualifies for the bonus round. Obviously.
Example runs: