57
\$\begingroup\$

Inspired by a task for programming 101 here's a task that hopefully isn't too easy or is a duplicate (kinda hard to search for things like this).

Input:

  • A positive integer n >= 1.

Output:

  • n lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line.

General rules:

  • This is code-golf, so shortest answer in bytes wins.
  • Since the course is taught in C++, I'm eager to see solutions in C++.

Test case (n=5):

*
**
***
****
*****
\$\endgroup\$
  • 6
    \$\begingroup\$ Not duplicate, just subset of Generate a right triangle. \$\endgroup\$ – manatwork Oct 10 '16 at 12:20
  • 2
    \$\begingroup\$ Training spaces allowed on each line? \$\endgroup\$ – Luis Mendo Oct 10 '16 at 12:33
  • 2
    \$\begingroup\$ Is a trailing new line acceptable? \$\endgroup\$ – Fatalize Oct 10 '16 at 12:34
  • 1
    \$\begingroup\$ Is a leading newline allowed? \$\endgroup\$ – Riley Oct 10 '16 at 14:38
  • \$\begingroup\$ I don't see a reason why not. \$\endgroup\$ – Sickboy Oct 11 '16 at 11:35

134 Answers 134

4
\$\begingroup\$

CJam, 13 11 10 bytes

Thanks to @MartinEnder for removing two bytes, and @Linus for removing one more!

ri{)'**N}%

Try it online!

Explanation

ri            e# Read input as an integer n
  {     }%    e# Run this block for each k in [0 1 ... n-1]
   )          e# Add 1 to the implicitly pushed k
    '*        e# Push asterisk character
      *       e# Repeat the character k+1 times
       N      e# Push newline
              e# Implicitly display
\$\endgroup\$
  • \$\begingroup\$ You can use map on number without taking the range to save another byte. \$\endgroup\$ – Linus Oct 31 '16 at 17:27
4
\$\begingroup\$

Pushy, 4 bytes

:42"

Try it online!

This method takes advantages of Pushy's automatic int/char conversion:

        \ Implicit: Input on stack
:       \ Input times do: (this consumes input)
 42     \   Push 42 (char '*')
   "    \   Print whole stack

Because each iteration adds a new * char, this outputs a triangle. For example, with n=4:

*       \   Stack: [42]
**      \   Stack: [42, 42]
***     \   Stack: [42, 42, 42]
****    \   Stack: [42, 42, 42, 42]
\$\endgroup\$
4
\$\begingroup\$

LaTeX, 171 bytes

I had to use LaTeX instead of plain TeX for the \typein macro...

Here it is, as golfed as I could:

\documentclass{book}\begin{document}\typein[\n]{}\newcount\i\newcount\a\i=0\loop{\a=0\loop*\advance\a by1\ifnum\i>\a\repeat}

\advance\i by1
\ifnum\n>\i\repeat\enddocument

Explanation:

\documentclass{book}% Book because it is shorter than article ;)
\begin{document}% Mandatory...
\typein[\n]{}% User inputs \n
\newcount\i% Create a line counter
\newcount\a% And an asterisk counter
\i=0% Initializes the line number to zero
\loop{% Line number loop
   \a=0% Sets the number of asterisks to zero
   \loop% Asterisk loop
   *% Prints the asterisk
   \advance \a by 1% Adds one to \a
   \ifnum\i>\a% If the line number is smaller than the number of asterisks
   \repeat% Then repeat
     }% Otherwise prints a new line

\advance\i by 1% And add 1 to the line counter
\ifnum\n>\i% If input number is less than the number of lines then
\repeat% Repeat
\enddocument% And finish LaTeX
\$\endgroup\$
4
\$\begingroup\$

Commodore 64/VIC-20 BASIC (and compatible C= 8-bits), ~77 tokenized BASIC bytes

0 INPUT"NUMBER OF *";A:ON-(A<1)GOTO1:J=1:FORI=1TOA:FORX=1TOJ:PRINT"*";:NEXTX:J=J+1:PRINT:NEXTI
1 :

Technically line 1 isn't required, but I'm mis-using the ON...GOTO command as a conditional GOTO in line zero so I added in the shortest possible line 1 to end it gracefully.

You will need to use Commodore keyword abbreviations to fit line zero on a C64, see the screen shot below (Note that the C128 in 128 mode might have different keyword abbreviations, but then you can enter more characters so you probably won't need it):

Commodore 64 asterisk printing simulator

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

Java 7 11, 88 73 58 bytes

String c(int n){return(n<2?"":c(n-1)+"\n")+"*".repeat(n);}

-15 bytes by converting to Java 11.

Try it online. (NOTE: String#repeat(int) is emulated as repeat(String,int) for the same byte-count, because TIO doesn't contain Java 11 yet.)

Explanation:

String c(int n){          // Recursive method with integer parameter and String return-type
  return(n<2?             //  If `n` is 1:
          ""              //   Start with an empty String
         :                //  Else:
          c(n-1)          //   Start with a recursive call with `n-1`
                +"\n")    //   and a trailing new-line
         +"*".repeat(n);} //  And append `n` amount of '*'
\$\endgroup\$
3
\$\begingroup\$

Batch, 69 bytes

@set s=
@for /l %%i in (1,1,%1)do @call set s=*%%s%%&call echo %%s%%
\$\endgroup\$
3
\$\begingroup\$

Ruby, 26 bytes

->n{s='';n.times{p s+=?*}}
\$\endgroup\$
3
\$\begingroup\$

Brainfuck, 70 bytes

,>++++++[<-------->>>+++++++<<-]<[>+[->+>.<<]>[-<+>]++++++++++.[-]<<-]

I'm sure this could be golfed a little bit. This version only works for single-digit numbers; feel free to modify it to work on larger numbers too.

Edit: If it's allowed to use a single character's ASCII value as the input, the resulting code is below. Only 60 bytes.

,>++++++[>>+++++++<<-]>[>+[->+>.<<]>[-<+>]++++++++++.[-]<<-]

Explanation:

,>++++++[<-------->>>+++++++<<-]  [this gets a single character from 
input into the first cell, subtracts 48 to convert it to an integer 
representation, and puts 42 in the 3rd cell (ASCII '*').]

<[ while the first cell is not zero do
    >+   add 1 to 2nd cell (empty when we start)
    [->+>.<<]  [while 2nd cell is not empty subtract 1 and print an *.
                Make a copy in 3rd cell.]
    >[-<+>]  copy 3rd cell value back to 2nd cell
    ++++++++++.[-] [put '\n' in 3rd cell, print, clear]
    <<-
 ] loop

Edit: Here is a version that works for numbers up to 255, reading the text representation of the number followed by EOF. If your favorite interpreter has unbounded cells it will work up to 999.

>>,[----------
[
    >++++++[<------>-]<--
>],]

[
 Pointer is one past the end of a run of digits containing input.
 Assumption: input < 256.
 Add ten times most significant digit to second and ten times the
 second to the third to get it in one cell.
]

<<<[>++++++++++<-]>[>++++++++++<-]>

Store 42 '*' in the cell 3 to the right
>>++++++[>+++++++<-]<<

[ While first cell is not empty
    >+ Add 1 to 2nd cell
    [->+>.<<] [make a copy in 3rd cell, print '*']
    >[<+>-] copy 3rd back to 2nd
    ++++++++++.[-] print newline and clear 3rd
    <<- subtract 1 from 1st and continue
]
\$\endgroup\$
  • \$\begingroup\$ IIRC you can take a character as input and use its ascii code \$\endgroup\$ – acrolith Oct 10 '16 at 16:51
  • \$\begingroup\$ Do you mean just use the input character to encode the number of rows in the triangle? Seems like it wouldn't work very well for small triangles since the low numbers are all control codes, not characters. \$\endgroup\$ – Sean McBane Oct 10 '16 at 18:09
  • \$\begingroup\$ Yes, but your code would be smaller and I've seen other BF answers using that. \$\endgroup\$ – acrolith Oct 10 '16 at 19:08
  • \$\begingroup\$ Where can I find the official rules for code golf on this site? \$\endgroup\$ – Sean McBane Oct 10 '16 at 19:44
  • \$\begingroup\$ How is it that my Clojure solution is exactly as long as a BrainFuck answer? -_- \$\endgroup\$ – Carcigenicate Oct 10 '16 at 21:45
3
\$\begingroup\$

Charcoal, 5 bytes

G↓→N*

It's the same length as Jelly, which is really bad for an ASCII-art oriented language. At least it's readable, I guess

Explanation

G      Polygon
 ↓→     Down, then right
   N   Input number
     *  Fill with '*'
\$\endgroup\$
3
\$\begingroup\$

Lua, 36 bytes

for i=1,...do print(("*"):rep(i))end

Takes input from the command line.

\$\endgroup\$
  • \$\begingroup\$ How exactly you run it? I always get only an error: “lua5.3: IDid.lua:1: 'for' limit must be a number”. \$\endgroup\$ – manatwork Oct 13 '16 at 7:55
  • \$\begingroup\$ @manatwork You can run it using e.g. lua IDid.lua 5 for 5 lines. \$\endgroup\$ – IDid Oct 13 '16 at 19:21
  • \$\begingroup\$ Indeed. Thanks. No idea what I combined earlier. (Was before coffee…) \$\endgroup\$ – manatwork Oct 13 '16 at 19:30
3
\$\begingroup\$

Haskell, 32 bytes

unlines.(`take`iterate('*':)"*")

The expression iterate('*':)"*" generates the infinite list ["*","**","***","****","*****",...]. The function then takes the first n elements and joins them with newlines.

The more direct

concat.(`take`iterate('*':)"*\n")

is one byte longer.

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

RProgN, 42 Bytes, Competing only for the Bounty

Q L c 's' = 
►3'rep'º'R'=]¿]s\R\1-]} [

The length of the script is used as the character code for *.

Try it Online!

\$\endgroup\$
  • \$\begingroup\$ Not sure if checking program length is borderline abusing the bounty rules or not... \$\endgroup\$ – Buffer Over Read Oct 14 '16 at 1:17
  • \$\begingroup\$ You're gonna need to represent an asterisk one way or another. The only other way, other than to assign an ordinal through some complex method is to pull it from a constant previously defined in the language, which RProgN lacks. \$\endgroup\$ – ATaco Oct 14 '16 at 1:18
  • \$\begingroup\$ Okay, I guess I'll get this one pass. Also, grabbing the asterisk from some predefined constant isn't allowed anyways. \$\endgroup\$ – Buffer Over Read Oct 14 '16 at 1:21
3
\$\begingroup\$

Perl, 83 76 bytes (no asterisk)

print substr((split("\n",`perldoc perlre`))[55],48,1)x$_."\n"foreach(1..<>);

(Faster version for large input, 83 characters):

$r=`perldoc perlre`;print substr((split("\n",$r))[425],11,1)x$_."\n"foreach(1..<>);

Explanation: The statement perldoc perlre executes the shell command to display the Perl documentation on regular expressions, which contains an asterisk as the 11th character on line 425. Split the resulting output by line, then extract that character and print in triangular format.

Edited to save 6 characters by not saving the output of the shell command, and instead just running it every time. It increases the runtime, though, but we only care about bytes, not runtime :) Another byte was saved (for a total of -7) by finding an earlier asterisk in the perldoc output.

\$\endgroup\$
  • \$\begingroup\$ Very awesome way of doing it, wow. \$\endgroup\$ – Buffer Over Read Oct 19 '16 at 18:36
3
\$\begingroup\$

ForceLang, 146 bytes

def S set
def G goto
S a io.readnum()
S b 0
label 0
if a=b
G 1
if b
io.writeln()
S b 1+b
S c 0
label b
io.write "*"
S c 1+c
if b=c
G 0
G b
label 1
\$\endgroup\$
3
\$\begingroup\$

Python 2, 38 37 bytes

There are only 36 characters shown, but a trailing newline is needed to avoid an EOF-related error raised by the interpreter. 1 byte knocked off for Flp.Tkc's observation.

for n in range(input()+1):print'*'*n

Output for n=5

# leading newline here
*
**
***
****
*****

Python 3, 45 bytes

The actual list comprehension is never assigned or printed, but if it were, it would be full of Nones, as None is the default return value of print().

[print('*'*n)for n in range(int(input())+1)]
\$\endgroup\$
  • \$\begingroup\$ Why not just use range? \$\endgroup\$ – FlipTack Dec 23 '16 at 15:35
  • \$\begingroup\$ Performance issues for very large triangles. range() in Python 2 returns a list containing all the integers, while xrange() returns a generator. I suppose for proof of concept range() does fine, but using xrange() when an actual list isn't necessary has become a habit for me. \$\endgroup\$ – James Murphy Dec 24 '16 at 5:56
  • 1
    \$\begingroup\$ I know the difference. But this is code-golf :P \$\endgroup\$ – FlipTack Dec 24 '16 at 9:18
3
\$\begingroup\$

TI-Basic, 28 22 bytes

Prompt A
"*
For(B,1,A
Disp Ans
Ans+"*
End
\$\endgroup\$
  • \$\begingroup\$ Prompt A "* For(B,1,A Disp Ans Ans+"* End for 22 bytes \$\endgroup\$ – pizzapants184 Sep 17 '17 at 19:46
  • \$\begingroup\$ Wow, I should have thought of that. Thanks @pizzapants184 \$\endgroup\$ – Timtech Sep 17 '17 at 20:48
3
\$\begingroup\$

Underload, 15 13 bytes

-2 or -3 bytes thanks to @ØrjanJohansen

(
)((*)~*:S)^

Input is a Church numeral inserted between the ) and ^ on the second line. For example:

(
)((*)~*:S)::*:**^

If printing a leading newline is allowed, the following solution works by ommiting the ~, for 12 bytes:

(
)((*)*:S)^
\$\endgroup\$
  • \$\begingroup\$ I think you can shorten this by two bytes by putting the newline in the starting string, or three (avoiding a ~) if an initial newline is permitted (the OP never completely clarified that.) \$\endgroup\$ – Ørjan Johansen Dec 29 '17 at 0:01
  • \$\begingroup\$ @ØrjanJohansen Thanks, edited. \$\endgroup\$ – Esolanging Fruit Dec 29 '17 at 1:40
3
\$\begingroup\$

R, 33 bytes

cat(strrep("*",1:scan()),sep="
")

Try it online!

I hope it's not a dupe - I was able to find only one other R answer. Leverages strrep and vectorization to build the vector "*","**",...,"******" and prints with cat using newline as a separator.

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

Pyke, 6 bytes

Voh\**

Try it here!

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

Brain-Flak, 81 bytes

78 bytes but three for the -A flag, which enables ASCII output.

{(({}[()])<>()){({}[()]<(((((()()()){}())){}{}){})>)}{}((()()()()()){})<>}<>{}

Try it online!

Brain-flak isn't the greatest language for ASCII-art, but it still managed to be somewhat short. Ish. Kinda.

Explanation:

While True:
{

(
Decrement counter
({}[()])

And move copy to other stack
<>())

Push N '*'s
{({}[()]<(((((()()()){}())){}{}){})>)}

Pop 0
{}

Push newline
((()()()()()){})

Move back to counter
<>

Endwhile
}

Move to other stack
<>

Pop an extra newline
{}
\$\endgroup\$
2
\$\begingroup\$

Actually, 8 bytes

R`'**`Mi

Try it online!

Explanation:

R`'**`Mi
R         range(1, n+1) ([1, 2, ..., n])
 `'**`M   for each element: that many asterisks
       i  flatten and implicitly print

5 bytes, non-competing

R'**i

Try it online!

This solution is non-competing because it relies on a bugfix released after this challenge was posted.

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

RProgN, 41 Bytes.

24 of these bytes are just assigning R and s, so that we can use a spaceless segment.

'rep' º 'R' = '*' 's' = ►]¿]s\R\1-]}[

Explination

'rep' º 'R' =       # Get the function for 'rep' (Replace), associate 'R' with it.
'*' 's' =           # Associate 's' with the string literal '*'
►                   # Begin spaceless segment.
    ]               # Push a copy of the top of the stack (The input)
    ¿               # While truthy, popping the top of the stack.
        ]           # Push a copy...
        s \ R       # Push an *, swap the two top values giving "i, *, i", Repeat the *, i times, giving "i, ****", or whatever.
        \ 1 -       # Swap the top values, giving "****, i", decrement the top value by 1.
        ]           # Push a copy of the top value.
    }[              # End the while, after processing, pop the top value (Which would be 0). Implcititly print.

Try it!

<style>
  #frame{
    width:60em;
    height:60em;
    border:none;
  }
</style>
<iframe id='frame' src="https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%27rep%27%20%C2%BA%20%27R%27%20%3D%20%27*%27%20%27s%27%20%3D%20%E2%96%BA%5D%C2%BF%5Ds%5CR%5C1-%5D%7D%5B&input=5">Sorry, You need to support IFrame. Why don't you..?</iframe>

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

Racket 47 bytes

(for((i(+ 1 n)))(displayln(make-string i #\*)))

Ungolfed:

(define (f n)
  (for ((i (+ 1 n)))                         ; (i 5) in 'for' produces 0,1,2,3,4 
    (displayln (make-string i #\*))))        ; #\* means character '*'

Testing:

(f 5)

Output:

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

Groovy, 27 characters

{1.upto(it){println"*"*it}}

Sample run:

groovy:000> ({1.upto(it){println"*"*it}})(5)
*
**
***
****
*****
===> null
\$\endgroup\$
  • \$\begingroup\$ {x->(1..x).each{println"*"*it}} was the one I was about to post before seeing this... 31 vs 27, I always forget about upto and the implicit it closure. \$\endgroup\$ – Magic Octopus Urn Oct 12 '16 at 16:41
  • 1
    \$\begingroup\$ @carusocomputing, yepp, I also usually forget about .upto, but this time IMP1's Ruby answer reminded it. \$\endgroup\$ – manatwork Oct 12 '16 at 16:58
2
\$\begingroup\$

jq, 19 characters

(18 characters code + 1 character command line option.)

range(1;.+1)|"*"*.

Sample run:

bash-4.3$ jq -r 'range(1;.+1)|"*"*.' <<< 5
*
**
***
****
*****

On-line test (Passing -r through URL is not supported – check Raw Output yourself.)

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

Ruby, 27 (or 24) bytes

(Thanks to m-chrzan for pointing out the miscounting.)

Returns a string.

->n{(1..n).map{|i|?**i}*$/}

the map makes an array of strings of * of increasing length. The *$/ takes the array and joins the elements to make a newline-separated string. If an array of strings is acceptable, these three bytes can be saved, scoring 24.

In test program

f=->n{(1..n).map{|i|?**i}*$/}
puts f[5]
\$\endgroup\$
  • \$\begingroup\$ I think arrays of strings are acceptable output by default. Also, I believe your current solution is only 27 bytes long, so it'll go down to 24 :D. \$\endgroup\$ – m-chrzan Oct 11 '16 at 12:07
2
\$\begingroup\$

Java, 110 bytes

Not that short, but I really like having empty for loops.

String f(int n){String s="";for(int i=0;i<n;i++,s+=new String(new char[i]).replace("\0","*")+"\n"){}return s;}
\$\endgroup\$
2
\$\begingroup\$

GameMaker Language, 68 bytes

a="*"for(i=2;i<=argument0;i++){a+="#"for(j=0;j<i;j++)a+="*"}return a
\$\endgroup\$
2
\$\begingroup\$

Prolog, 60 58 56 bytes

g(N):-N<=0,put(*),g(N-1);!.
f(N):-N<=0,f(N-1),g(N),nl;!.

I'm not that familiar with Prolog, but I just gave it a shot. I'm sure it can be a lot shorter.

Put the code into a file, then load that file into swipl and run f(25). (or some other number).

EDIT: quotes can be left out in put statement
EDIT 2: changing =:= to <= saves 2 bytes. I tried inverting it, but that'd make it wait for a return for some reason.

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

Elixir, 81 bytes

&Enum.reduce(Enum.to_list(1..&1),"",fn(x,r)->r<>String.duplicate("*",x)<>"\n"end)

Anonymous function using the capture operator. Enum.reduce will iterate a list (the list is obtained by calling Enum.to_list on the range 1..n) and concatenate the return string r (which has been initialized with "") with a string made of x asterisks and a newline.

Full program with test case:

s=&Enum.reduce(Enum.to_list(1..&1),"",fn(x,r)->r<>String.duplicate("*",x)<>"\n"end)
IO.write s.(5)

Try it online on ElixirPlayground !

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