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

10
\$\begingroup\$

CJam, 10 bytes

r{,'**Nr}h

How it works:

r{     r}h         e# This do-while loop basically reads all the whitespace separated tokens
                   e# from input. It separates the tokens on running lengths of whitespace
  ,                e# Take the length of the token
   '**             e# Get a string of that many '*' characters
      N            e# Print a new line

Try it online here

\$\endgroup\$
24
\$\begingroup\$

Retina, 5 + 3 = 8 bytes

 +
\n
.
*

Every line goes in its own file, so I've added 1 byte for each additional file. Also, the \n should be replaced with an actual newline.

Each pair of lines is a pattern-replacement pair. + matches one or more spaces and replaces it with a newline. . matches any character except a newline, and it replaces that with a *. This is applied globally, so every character is replaced with a *.

\$\endgroup\$
6
\$\begingroup\$

R, 38 bytes (with some help in comments)

cat(gsub(" +|$","\n",gsub("\\S","*",x)))

How it works

  • gsub replaces all no-spaces with *
  • second gsub adds \n (newline) to the end of each element
  • cat prints accordingly

Demo

\$\endgroup\$
6
\$\begingroup\$

Perl, 16 bytes (15 chars + -p)

y/ /
/s;s/./*/g

Run as:

$ perl -pe 's/ +/
/g;s/./*/g' <<< 'This is a test'
****
**
*
****

Saved an additional byte, thanks to @ThisSuitIsBlackNot, I hadn't encountered y///s before!

\$\endgroup\$
  • \$\begingroup\$ This is excellent! You can save 1 byte by changing the first substitution to a transliteration: y/ /\n/s; \$\endgroup\$ – ThisSuitIsBlackNot Sep 8 '15 at 21:41
  • \$\begingroup\$ @ThisSuitIsBlackNot Ooh nice! thank you! \$\endgroup\$ – Dom Hastings Sep 8 '15 at 21:44
11
\$\begingroup\$

Pyth, 9 bytes

jm*ld\*cz

Explanation:

jm*ld\*cz
       cz    chop input on whitespace
 m           map to
   ld        length of the segment
  *  \*      number of asterisks
j            joined on newlines
\$\endgroup\$
2
\$\begingroup\$

SWI-Prolog, 40 bytes

a([A|T]):-(A=32,nl;put(42)),(T=[];a(T)).

Called with code strings, e.g. a(`This is an example histogram of word length`).

\$\endgroup\$
3
\$\begingroup\$

Python 3, 72 bytes

A nice one liner :)

print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split())))

Output:

>>> print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split())))
Hello world  how are you?
*****
*****
***
***
****

There's a trailing newline here. If you want it without, you've got to add 5 bytes:

print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split()))[:-1])
\$\endgroup\$
6
\$\begingroup\$

Javascript ES6

Function, 46 chars

f=s=>s.replace(/\S/g,'*').replace(/\s+/g,'\n')

Program, 55 chars

alert(prompt().replace(/\S/g,"*").replace(/\s+/g,"\n"))
\$\endgroup\$
  • \$\begingroup\$ Your function is actually 46 characters long, and your program is 55. \$\endgroup\$ – adroitwhiz Sep 7 '15 at 21:06
  • \$\begingroup\$ @darkness3560, thank you for the correction. I used expressions like "f=s=>s.replace(/\S/g,'*').replace(/\s+/g,'\n')".length to measure the length and forgot about \. \$\endgroup\$ – Qwertiy Sep 7 '15 at 22:21
10
\$\begingroup\$

Python 3, 43 bytes:

for w in input().split():print('*'*len(w))

Thanks to @BetaDecay for pointing out a syntax error.

Sample run:

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

(The string below is entered as a literal, rather than as text)

> 'example\twith\nweird\rwhite   space'
*******
****
*****
**********

Bonus: vertical histogram

Thanks to @Caridorc for pointing out my error that made the bonuses have 1 to many rows.

l=[len(x)for x in input().split()]
for i in range(len(l)-1,0,-1):print(''.join(['*'if j>=i else' 'for j in l]))

Demo:

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

Bonus: vertical histogram (upside down)

l=[len(x)for x in input().split()]
for i in range(len(l)-1):print(''.join(['*'if j>i else' 'for j in l]))

Demo:

> This is an example histogram of word length
********
********
*  ** **
*  ** **
   **  *
   **  *
   **   
\$\endgroup\$
  • \$\begingroup\$ Vertical is off by one \$\endgroup\$ – Caridorc Sep 7 '15 at 19:03
4
\$\begingroup\$

Java, 102 bytes

class R{public static void main(String[]a){for(String s:a)System.out.println(s.replaceAll(".","*"));}}
\$\endgroup\$
2
\$\begingroup\$

STATA, 72 bytes

di _r(a)
token "$a"
while ("`1'")!=""{
di _d(`=length("`1'")')"*"
ma s
}

Ungolfed

display _request(a) //get input via prompt
tokenize "$a" //split a by spaces into the variables 1,2,...
while ("`1'")!=""{ //while the first variable is not empty
display _dup(`=length("`1'")')"*" //display "*" duplicated for every character in variable 1.
macro shift //move variable 2 to 1, 3 to 2, etc.
}

Note that this code does not work in the online interpreter and requires the non-free proprietary STATA interpreter.

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

Gema, 11 9 characters

 =\n
?=\*

Sample run:

bash-4.3$ gema ' =\n;?=\*' <<< 'This is an example histogram of word length'
****
**
**
*******
*********
**
****
******

bash-4.3$ gema ' =\n;?=\*' <<< 'a aa aaa aaaa aaaaa'
*
**
***
****
*****

bash-4.3$ gema ' =\n;?=\*' <<< 'double space  example'
******
*****
*******
\$\endgroup\$
4
\$\begingroup\$

Haskell, 31 bytes

putStr.unlines.map(>>"*").words

Usage example:

Main> putStr.unlines.map(>>"*").words $ "This is an example histogram of word length"
****
**
**
*******
*********
**
****
******
\$\endgroup\$
  • \$\begingroup\$ you could replace putStr. with f= to lower the byte count, or use main=interact$ instead of putStr. to read from STDIN and make it a complete program \$\endgroup\$ – HEGX64 Sep 9 '15 at 13:31
  • \$\begingroup\$ @HEGX64: but f=unlines.map(>>"*").words returns something like "****\n**\n**\n" and does not output a "horizontal ASCII art graph" as requested. \$\endgroup\$ – nimi Sep 9 '15 at 16:04
6
\$\begingroup\$

><>, 38 37 Bytes

Curse you double space case *shakes fish*.

<v&0
 >i:84*=?v0(?;67*o&1&
 \ &0o?&a/

You can try it online (all you need to do is give input through the field near the bottom and then hit the Give button). Suggestions for further golfing are always welcome, especially ideas to remove those wasteful spaces in front of the second and third lines.

If you were allowed to print an additional newline for extra spaces, the code could be a whopping 27 bytes:

>i:84*=?v0(?;67*o
^     oa<

Explanation

Note: the order of the explanation will correspond to the pointer's location (so if the code is explained out of what one would consider order, it is because it is the order in which the pointer executes it).

Line 1:

<v&0
<      redirects flow leftward
   0   pushes 0 onto the stack
  &    pops 0 and puts it in the register 
 v     redirects flow downward

Line 2:

>i:84*=?v0(?;67*o&1&
>                     redirects flow leftward
 i:                   pushes input and then duplicates it
   84*                pushes 32 (the space character numerically)
      =?v             pops 32 and input and redirects flow downward if they're equal
         0(?;         pops input and terminates if input is less than 0*
             67*o     pushes 42 (asterisk) and prints it
                 &1&  pushes register value and then puts 1 in the register

*in ><>, the command i returns -1 if no input is given

Line 3:

N.B. This line goes in reverse, so read right to left.

 ^ &0o?&a<
         <  redirects flow leftward
        a   pushes 10 (newline) onto the stack
     o?&    prints a newline if the register is not 0
   &0       sets the register to 0
 ^          redirects flow upwards (back to the second line)

Basically, the program test to make sure the input (which is read one character at a time) is not a space and then prints an asterisk. It terminates if there is no input (the input value is -1). To make sure it doesn't print additional newlines, it uses the register value, which it either sets to 0 or 1. Because of the way I set it up, it doesn't care about the extraneous values pushed onto the stack (e.g. the value of the register when it sets it to 1 after printing an asterisk); they remain on the stack when the program terminates but do nothing.

I know it might be a bit confusing since I used 84* and 67* instead of " " and "*" respectively, but that was because I didn't feel like putting strings in the program for whatever reason.

\$\endgroup\$
2
\$\begingroup\$

C++14, 107 106 bytes

#include<iostream>
main(){std::string s;for(;std::cin>>s;){for(char c:s)std::cout<<'*';std::cout<<'\n';}}
\$\endgroup\$
4
\$\begingroup\$

CJam, 11 bytes

Competing for second place in CJam after @Optimizer found a clever 10 byte solution. This is a straightforward 11 byte solution:

lS%:,'*f*N*

Try it online

Alternate solution that uses a loop instead of the two maps, also 11 bytes:

lS%{,'**N}/

Explanation for first solution:

l     Get input.
S%    Split at spaces.
:,    Apply length operator to each word.
'*f*  Map each length to corresponding repetitions of '*.
N*    Join with newlines.
\$\endgroup\$
10
\$\begingroup\$

R - 33

write(gsub(".","*",scan(,"")),"")

where

  • scan(,"") reads from stdin and splits on white-space into a character vector.
  • gsub(".", "*", ...) replaces all characters into *.
  • write(..., "") prints to stdout with "\n" as the default separator.
\$\endgroup\$
3
\$\begingroup\$

Javascript (ES6)

New solution (39 bytes):

s=>[...s].map(c=>c==' '?`
`:'*').join``

Regex solution (42 bytes):

s=>s.replace(/\S/g,"*").replace(/ +/g,`
`)

Non-regex solution (71 bytes):

s=>s.split(" ").map(v=>"*".repeat(v.length)).filter(a=>a!="").join(`
`)

These solutions define anonymous functions. Assign them to variables or call them like so:

(s=>s.replace(/\S/g,"*").replace(/ +/g,`
`))("[your string here]")

(s=>s.split(" ").map(v=>"*".repeat(v.length)).filter(a=>a!="").join(`
`))("[your string here]")
\$\endgroup\$
3
\$\begingroup\$

Julia, 50 bytes

s->print(join(["*"^length(w)for w=split(s)],"\n"))

This creates an unnamed function that takes a string as input and prints to STDOUT.

Ungolfed:

function f(s::String)
    # Construct a vector of horizontal bars
    bars = ["*"^length(w) for w in split(s)]

    # Join the bars with newlines
    j = join(bars, "\n")

    # Print the result to STDOUT
    print(j)
end
\$\endgroup\$
4
\$\begingroup\$

JavaScript (ES6), 37

f=s=>s.replace(/./g,m=>m<"!"?`
`:'*')

Shorter version using only one replace.

\$\endgroup\$
  • 2
    \$\begingroup\$ Dammit, I just finished my ES6 function, 38 bytes. Take my upvote while I run away in shame! :D \$\endgroup\$ – MayorMonty Sep 8 '15 at 6:30
5
\$\begingroup\$

PHP 5.3, 55 53 51 50 bytes

<?for(;$i<strlen($a);){echo$a{$i++}!=' '?'*':"
";}


Usage:
Call the Script and define a global variable ($a)
php -d error_reporting=0 script.php?a="This is an example histogram of word length"

Output:

****
**
**
*******
*********
**
****
******
\$\endgroup\$
3
\$\begingroup\$

Matlab / Octave, 75 bytes

Using an anonymous function:

@(s)char(arrayfun(@(n)repmat('*',1,n),diff([0 find([s 32]==32)])-1,'un',0))

Thanks to Hoki for spotting a mistake which prevented the last word from being detected.

Example use (Matlab):

>> @(s)char(arrayfun(@(n)repmat('*',1,n),diff([0 find([s 32]==32)])-1,'un',0)) % define function
ans = 
    @(s)char(arrayfun(@(n)repmat('*',1,n),diff([0,find([s,32]==32)])-1,'un',0))
>> ans('This is an example histogram of word length') % call function
ans =
****     
**       
**       
*******  
*********
**       
****     
******   

Or try it online (Octave).

\$\endgroup\$
3
\$\begingroup\$

PowerShell, 35 31 Bytes

Pretty competitive for a change. Go go gadget unary operators. I also keep forgetting that parens on some functions, like the -split and -replace used here, are optional.

%{$_-split"\s+"-replace".","*"}

Called via pipeline input (equivalent to stdin for PowerShell):

PS C:\Tools\Scripts\golfing> "a aa aaa" | %{$_-split"\s+"-replace".","*"}
*
**
***

As a bonus, if we can instead use command-line arguments, we can get down to 20 Bytes and have something that works both with and without a single-string as input:

$args-replace".","*"

PS C:\Tools\Scripts\golfing> .\horizontal-graph-word-length.ps1 "double space  example"
******
*****
*******

PS C:\Tools\Scripts\golfing> .\horizontal-graph-word-length.ps1 double space  example
******
*****
*******
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES5)

Program, 54 chars

alert(prompt().replace(/\S/g,'*').replace(/ +/g,'\n'))

Function, 60 chars

function(i){return i.replace(/\S/g,'*').replace(/ +/g,'\n')}

Example usage:

var h=function(i){return i.replace(/\S/g,'*').replace(/ +/g,'\n')},
d=document,g=d.getElementById.bind(d),i=g('i'),o=g('o')
i.onchange=function(){o.textContent=h(i.value)}
<input id="i"/>
<pre id="o"></pre>

\$\endgroup\$
3
\$\begingroup\$

Matlab - 54 bytes

s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)

This runs from the console, will take a string in input from stdin and will output the horizontal word graph in stdout:

Exemple:

>> s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
'This is an example histogram of word length'
o =
****
**
**
*******
*********
**
****
******

Or we could try to make some fancy shapes:

>> s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
'a aa aaa aaaaaa aaaaaaaaaa aaaaaaaaaaa aaaaaaaaaa aaaaaa aaa aa a aa aaa aaaaaa aaaaaaaaaa'
o =
*
**
***
******
**********
***********
**********
******
***
**
*
**
***
******
**********
\$\endgroup\$
  • \$\begingroup\$ Very clever approach! \$\endgroup\$ – Luis Mendo Sep 9 '15 at 13:01
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\$
1
\$\begingroup\$

Bash - 60 26 bytes

new solution (thanks manatwork):

for w;{ echo "${w//?/*}";}

old solution:

for w;do for((i=1;i<=${#w};i++));do printf \*;done;echo;done

~ $ ./l This is an example histogram of word length
****
**
**
*******
*********
**
****
******

The only part that might deserve an explanation is ${#w}: it returns the length of the string w.

\$\endgroup\$
  • \$\begingroup\$ Processing separate parameters instead of a single input to avoid completing half of the task, is kind of cheating. Anyway, what you wrote there, can be accomplished in 26 characters: for w;{ echo "${w//?/*}";} \$\endgroup\$ – manatwork Sep 9 '15 at 15:12
  • \$\begingroup\$ Yeah, I realized this was basically a character substitution just after posting that, so I posted another one in sed: codegolf.stackexchange.com/a/57435/7176 \$\endgroup\$ – 1ace Sep 9 '15 at 15:15
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
3
\$\begingroup\$

J, 10 bytes

   '*'$~$&>;:'This is an example histogram of word length'
****     
**       
**       
*******  
*********
**       
****     
******

Bonus: vertical (12 bytes)

   |:'*'$~$&>;:'This is an example histogram of word length'
********
********
*  ** **
*  ** **
   **  *
   **  *
   **   
    *   
    *   

Bonus: flipped vertical (14 bytes)

   |.|:'*'$~$&>;:'This is an example histogram of word length'
    *   
    *   
   **   
   **  *
   **  *
*  ** **
*  ** **
********
********
\$\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.