28
\$\begingroup\$

Input

A list of words separated by any number of spaces.

Output

A horizontal ASCII art graph, where the n-th line is composed by as many asterisks (*) as the n-th word is long.

Example usage

The > signals user input, you should not input it when testing the program.

> This is an example histogram of word length
****
**
**
*******
*********
**
****
******

> a aa aaa aaaa aaaaa
*
**
***
****
*****

> double space  example
******
*****
*******

Reference implementation

In case of doubt over the specification, the output of your program should match exactly that of the below program under all inputs.

puts gets.chomp.split.map{|word| '*' * word.length}.join("\n")
\$\endgroup\$
  • \$\begingroup\$ So is a trailing newline allowed? crosses fingers \$\endgroup\$ – Beta Decay Sep 7 '15 at 14:15
  • \$\begingroup\$ @BetaDecay Yes, allowed ........... \$\endgroup\$ – Caridorc Sep 7 '15 at 15:10
  • \$\begingroup\$ Will the input ever have leading or trailing spaces? \$\endgroup\$ – PhiNotPi Sep 7 '15 at 15:20
  • 8
    \$\begingroup\$ What you're describing is not a histogram. A histogram would show the number of words with x characters on line x. In the first example, line 1 would have 0 asterisks (no words with length 1) line 2 would have 3 asterisks (is, an, of) and so on. \$\endgroup\$ – nitro2k01 Sep 7 '15 at 20:50
  • 1
    \$\begingroup\$ Ok, I realize you're right. Horizontal it is. \$\endgroup\$ – nitro2k01 Sep 7 '15 at 21:08

33 Answers 33

1
\$\begingroup\$

sed - 20 bytes

s/[^ ]/*/g;s/ +/\n/g

~ $ sed -re 's/[^ ]/*/g;s/ +/\n/g' <<< 'This is an example histogram of word   length'
****
**
**
*******
*********
**
****
******
\$\endgroup\$
  • \$\begingroup\$ @jimmy23013: I edited my answer accordingly, and fixed the multiple space issue :) \$\endgroup\$ – 1ace Sep 10 '15 at 9:12
0
\$\begingroup\$

AWK

 awk '{for(i=1;i<=NF;i++){while(k++<length($i)){printf "*"};k=0;print ""}}'

examples

 echo "this is programming" | awk '{for(i=1;i<=NF;i++){while(k++<length($i)){printf "*"};k=0;print ""}}'

output:-

****
**
***********
\$\endgroup\$
0
\$\begingroup\$

Ruby, 29 bytes

puts gets.gsub(/\S/,?*).split
\$\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.