Draw an asterisk triangle

59

4

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):

*
**
***
****
*****

Sickboy

Posted 9 years ago

Reputation: 1 075

6

Not duplicate, just subset of Generate a right triangle.

– manatwork – 9 years ago

2Training spaces allowed on each line? – Luis Mendo – 9 years ago

2Is a trailing new line acceptable? – Fatalize – 9 years ago

1Is a leading newline allowed? – Riley – 9 years ago

I don't see a reason why not. – Sickboy – 9 years ago

For the new challenge, I recommend posting in the sandbox first. I find it very useful for my challenges, even if they seem finished already.

– trichoplax – 9 years ago

In the comments you said that a leading new line is allow, but the spec now requires one asterisk in the first line. Which is it? – Riley – 9 years ago

Riley: You can do both, as you please; trichoplax: Thanks, already saw the sandbox :-); Dennis: thanks fr the info! – Sickboy – 9 years ago

Is a preceding new line acceptable? – Stan Strum – 8 years ago

This has already been asked: yes, it is. – Sickboy – 6 years ago

Answers

41

Vim, 8 bytes

o <Esc><C-V>{r*J

Takes input in the readahead buffer, so if input is 15, you would type that and then the code above. This is a silly rule, but seems to be allowed. If you got input in a register like "a, you'd just stick @a in front (10). If you got it from the start file, you'd prepend D@" instead (11).

Relies on abuse of :set autoindent, which is default in vimgolf.com rules and default in Vim 8 (and everyone uses it anyway).

  • o <Esc>: With its number argument, if your text starts with whitespace, and you have :set autoindent, Vim glitches out and creates a cascade of indent.
  • <C-V>{r*: Turn all those spaces into *s. I'm using block visual so that, even if your lousy indent settings silently group your spaces into tabs, you'll still get the right number of *s.
  • J: Starting with o unfortunately left a blank line at the top. This removes it.

udioica

Posted 9 years ago

Reputation: 2 381

1This answer is insanely impressive. One of the coolest vim answers I've seen. – James – 9 years ago

1It looks like a fish. Or a rocket. – Stephan Bijzitter – 9 years ago

1I twitched a little bit and fired Vim with -u NONE to see this by myself... It didn't work, it seems autoindent is on in the default vimrc, not vim 8 itself so I had to turn it in manually. But, hats off for the ingenuity of this answer! But why is there only one space per new line? Why does it only work with spaces but not with other characters? I still have much to learn it seems :) – Christian Rondeau – 9 years ago

Starting with O <Esc> won't require J at the end. – primo – 9 years ago

@primo That leaves an extra blank line at the end, instead of the beginning. – udioica – 9 years ago

1@udioica a single trailing newline is generally considered acceptable. – primo – 9 years ago

You might be able to remove the J and cut it down to 7 bytes. OP seemingly allowed a leading newline in the comments of the question. – Zach Gates – 8 years ago

23

JavaScript (ES6), 31 bytes

This one includes both a leading and a trailing line-break.

We start with a string s containing only a line-break. Then we process n recursive calls, adding an asterisk on the left side of this string at each iteration. The concatenation of all intermediate strings leads to the expected result.

f=(n,s=`
`)=>n?s+f(n-1,'*'+s):s

Without asterisk, 36 bytes

f=(n,s=`
`)=>n?s+f(n-1,atob`Kg`+s):s

Arnauld

Posted 9 years ago

Reputation: 111 334

How does it work ? – Alexis_A – 9 years ago

1@Alexis_A - I've added a short description. – Arnauld – 9 years ago

3Nice recursive answer; I never would have thought of the technique you use with s. You can make it slightly less cryptic with n?s+f(n-1,'*'+s):s. – ETHproductions – 9 years ago

19

05AB1E, 7 6 bytes

Uses CP-1252 encoding.

'*×.p»

8 byte no-asterisk version:

žQTè×.p»

Try it online!

Explanation

Example using input n = 5

'*      # push "*"
        # STACK: "*"
  ×     # repeat input number times
        # STACK: "*****"
   .p   # get prefixes of string
        # STACK: ['*', '**', '***', '****', '*****']
     »  # join by newlines
        # implicit print

Emigna

Posted 9 years ago

Reputation: 50 798

@TheBitByte 10žQSè×.p» is a logical extension of this answer to get what you wanted for the bounty and it is only 10 bytes. Give Emigna the bounty if nobody beats 10 bytes haha. – Magic Octopus Urn – 9 years ago

1@carusocomputing: TžQè×.p» is 8 bytes even. – Emigna – 9 years ago

Still trying to learn the language, missed the T instruction; thought it was odd that there was a ton of Base2 pushes but no base 10. I have to still scour the entire contents of the info.txt to be able to do anything in that language heh. – Magic Octopus Urn – 9 years ago

@carusocomputing some commands are really easy to miss, especially if you know another way to do it :) – Emigna – 9 years ago

So strings are automatically vectorized as lists if you push a list command as well? Is that why S wasn't needeD? – Magic Octopus Urn – 9 years ago

1@carusocomputing: Not sure what you are referring to. The only list command I'm using here is » and that is a command specifically for merging a lists with delimiters into a string (and S would ruin that). But a lot of 05AB1E commands do vectorize, yes. – Emigna – 9 years ago

@Emigna you can use this for your no-asterick version, for 7 bytes: 42ç×.p» – Okx – 9 years ago

@Okx: The no-asterisk version was for a bounty and 42 was specifically disallowed for that, which is why I'm using žQTè instead. Otherwise that would certainly have been a better version :) – Emigna – 9 years ago

@Emigna Oh, I didn't realise, it seems the bounty has been edited out. – Okx – 9 years ago

@Okx: It was actually never a part of the question, only as a bounty, so there is no way (that I know of) to actually see it anymore which make all the "no-asterisk" versions a bit confusing. – Emigna – 9 years ago

5 bytes: '*×ƶ» (dunno if ƶ existed back then) – Mr. Xcoder – 8 years ago

@Mr.Xcoder: ƶ is much newer than this challenge, yeah. – Emigna – 8 years ago

@Mr.Xcoder '*×η» too, .p has a 1-byte now as well ;). – Magic Octopus Urn – 7 years ago

Another 5-byter, but this one should also have been possible at the date your answer was posted in the legacy version: L'*×» / L'**» – Kevin Cruijssen – 6 years ago

15

PowerShell, 21 bytes

1..$args[0]|%{'*'*$_}

Loops from 1 to input $args[0], each iteration using string multiplication to construct a string of that many $_ asterisks. Default behavior for the implicit Write-Output at the end is with a newline for separator, so we get that for free.

PS C:\Tools\Scripts\golfing> .\draw-asterisk-pattern.ps1 5
*
**
***
****
*****

PS C:\Tools\Scripts\golfing> .\draw-asterisk-pattern.ps1 2
*
**

PS C:\Tools\Scripts\golfing> .\draw-asterisk-pattern.ps1 7
*
**
***
****
*****
******
*******

AdmBorkBork

Posted 9 years ago

Reputation: 41 581

13

Jelly, 6 5 bytes

”*ẋþY

TryItOnline

How?

”*ẋþY - Main link: n
”*    - literal string "*"
   þ  - form outer product with the dyadic function:
  ẋ   -     repeat list (right input is an implicit range(n), Jelly defaults to 1-based)
            so the outer product is like:
            [[i*'*' for i in range(1,len("*")+1)] for x in range(1,n+1)]
    Y - join with line feeds
      - implicit print

Bounty:
I'm not sure what the no ordinals clause is, since a character is a lookup of an ordinal.
Direct lookup would just be 42Ọẋþ³Y for 7 bytes - where the ³ gets us the input)
A short slightly indirect method would be, for 8 bytes, “)’Ọẋþ³Y - where we lookup ')' in jelly's code page, which is 1-indexed so “)’ yields 42.

Jonathan Allan

Posted 9 years ago

Reputation: 67 804

something interesting happens when you use a leading 0 in the input, eg. try "0414141" as an input. I'm clueless at golf languages so I wouldn't know where to begin trying to explain it. – Luke – 9 years ago

I think it is evaluated as a string and hence iterates across across it as a string is an iterable and then each character evaluates to an integer as they are all digits (it will error with "hi" for example) – Jonathan Allan – 9 years ago

13

Python 2, 37 34 bytes

i=1;exec"print'*'*i;i+=1;"*input()

Ideone

i is initialised to 1;
then exec commands to execute the following string of code, so it must be constructed;
the string is "print'*'*i;i+=1;" but the * following the string takes precedence over the exec and instructs to first repeat the string input() times;
the exec command now executes the long string which acts like a loop, printing another string of increasing length, again using * to repeat the character '*', then incrementing i with i+=1.

Python 3, 41 bytes:
def f(n):i=1;exec("print('*'*i);i+=1;"*n); or
lambda n,i=1:exec("print('*'*i);i+=1;"*n)

Jonathan Allan

Posted 9 years ago

Reputation: 67 804

11

C#, 42 bytes

f=n=>n<1?"":f(n-1)+"\n"+new string('*',n);

Full program with test case:

using System;

namespace DrawAnAsteriskPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,string>f= null;
            f=n=>n<1?"":f(n-1)+"\n"+new string('*',n);

            Console.WriteLine(f(5));
        }
    }
}

adrianmp

Posted 9 years ago

Reputation: 1 592

You need it since it's a recursive function. – adrianmp – 9 years ago

right. Didn't see that – Cyoce – 9 years ago

10

Pyth, 6 bytes

j._*"*

Try it here.

Explanation

j            Join by newlines
 ._          all prefixes of
    *        the result of repeating
      "*     the string "*"
             as many times as the implicit input 

Luis Mendo

Posted 9 years ago

Reputation: 87 464

3My first Pyth answer – Luis Mendo – 9 years ago

9

GNU sed, 25 24 20 + 1(n flag) = 21 bytes

Edit: 4 bytes less based on Riley's comments

x;G;:;P;s:\n.:*\n:;t

Try it online!

Run example: the input is in unary format, which for sed is allowed based on this consensus

me@LCARS:/PPCG$ sed -nf draw_triangle.sed <<< "0000"

*
**
***
****

A leading newline is present in the output, but this is allowed by the OP.

Explanation:

x;G             # prepend a newline to unary string
:               # start loop
   P            # print first line only
   s:\n.:*\n:   # shift one unary char from 2nd line to 1st, converted to a '*'
t               # repeat

seshoumara

Posted 9 years ago

Reputation: 2 878

If you Print before the substitution and a leading newline is allowed you don't need /0$/. If a newline isn't allowed you can still save a byte with x;G;:;/*/P;s:\n.:*\n:;t. I asked about a leading newline, but haven't heard back yet. – Riley – 9 years ago

8

Matlab, 26 23 bytes

Good old Matlab...

@(n)tril(repmat('*',n))

Has trailing whitespaces. tril gives you the lower triangular matrix.

edit: saved 2 bythes thanks to Luis Mendo

mathause

Posted 9 years ago

Reputation: 341

You are right - thanks - still not very competitive :P – mathause – 9 years ago

8

C++ - 92 96 Bytes

#include<string>
int main(){int n;std::string s;scanf("%d",&n);for(;n--;)puts((s+="*").data());}

Try it online

Ungolfed:

//this one hurts, but c++ strings are mutable
#include<string> 
int main(){
    int n;
    //this one hurts as well
    std::string s; 
    //read input to n
    //longer than 'std::cin>>n', but no #include<iostream> needed
    scanf("%d",&n); 
    // same as 'while(n--)', also characterwise, but way cooler
    for(;n--;) 
        //add a '*' the string
        //data() does the same as c_str()
        //puts automatically adds an '\n'
        puts((s+="*").data()); 
}

Anedar

Posted 9 years ago

Reputation: 311

should be 'int main(){}' for +4 bytes. – None – 9 years ago

true, damn - so non-standard behaviour of gcc/ideone – Anedar – 9 years ago

7

Jellyfish, 12 11 9 bytes

\P$'*
  i

Try it online!

Explanation

The above program is equivalent to the following functional pseudocode:

\            P      $       i        '*
map_prefixes(print, reshape(input(), '*'))

The $ (reshape) creates a string of N asterisks. \P creates a function which takes a list (or string) and passes each of its prefixes to P (print). Hence, this successively prints strings of 1 to N asterisks.

Martin Ender

Posted 9 years ago

Reputation: 184 808

7

R, 45 bytes

For loop approach:

for(i in 1:scan())cat(rep("*",i),"\n",sep="")

Billywob

Posted 9 years ago

Reputation: 3 363

6

Brachylog, 12 bytes

yke:"*"rj@w\

Try it online!

This assumes that a trailing new line is acceptable

Explanation

yk                The range [0, …, Input - 1]
  e               Take one element I of that range
   :"*"rj         Juxtapose "*" I times to itself
         @w       Write that string followed by a new line
           \      False: backtrack to another element of the range

No trailing new line, 15 bytes

-:"*"rj:@[f~@nw

Try it online!

This one works by taking all prefixes of "*" × Input.

Fatalize

Posted 9 years ago

Reputation: 32 976

6

Haskell, 35 38 bytes

List comprehension thanks to nimi:

f x=unlines[[1..n]>>"*"|n<-[1..x]]

Old version:

f 0=""
f n=f(n-1)++([1..n]>>"*")++"\n"

Alternate version:

g n=([1..n]>>"*")++"\n"
f n=[1..n]>>=g

Craig Roy

Posted 9 years ago

Reputation: 790

You can use ([1..n]>>"*") instead of replicate n'*' to save a byte. I also count only 39 bytes. – Laikoni – 9 years ago

Nice alternate version! However I think the byte count is still of by one and should be 38. (See e.g. here) The problem might be the newline after f 0="" which is counted as one byte, but shown as two bytes/characters in some text editors.

– Laikoni – 9 years ago

Thanks! I see now that I was initially adding a trailing newline when I was counting the characters. Wont make that mistake again! – Craig Roy – 9 years ago

2You can switch to a list comprehension: f x=unlines[[1..n]>>"*"|n<-[1..x]]. – nimi – 9 years ago

6

Pyth, 7 Bytes

VQ*\*hN

Knocked off a byte thanks to @ETHproductions Try it online

using @PIetu1998's Technique

6, bytes

j*L*\*S

Dignissimus - Spammy

Posted 9 years ago

Reputation: 449

Nice answer! You can replace "*" with \*. – ETHproductions – 9 years ago

@ETHproductions I never knew about that, thanks! – Dignissimus - Spammy – 9 years ago

You can remove another byte with a map. j*L\*S (incluSive range, multiply each *L by "" `\,j`oin by newline) Pyth inserts an implicit Q in the end. – PurkkaKoodari – 9 years ago

jm*\*h is also 6 bytes. – hakr14 – 8 years ago

6

Brain-Flak 75 Bytes

Includes +3 for -A

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

Try it online!


Explanation:

{(({})[()]<                                                        >)}
#reduce the top element by one until it is 0 after doing the following
#Push this element back on to act as a counter for the next step.
#(counts down from input to 0 we'll call this counter)

           {({}[()]<                          >)}
           #reduce the top element by one until it is 0 after doing the following
           #(counts down from counter to 0)

                    (((((()()()){}()){})){}{})  
                    #push 42 (the ASCII code for *)

                                                 {}
                                                 #pop the counter used to push
                                                 #the right number of *s

                                                   ((()()()()()){})
                                                   #push a 10 (newline)

                                                                      {}
                                                                      #pop the null byte

Riley

Posted 9 years ago

Reputation: 11 345

this includes a null byte in output? I don't think that is allowed... – Destructible Lemon – 9 years ago

Nope, I mean a null byte – Destructible Lemon – 9 years ago

@DestructibleWatermelon Yeah, I guess it does. Easy fix though. Thanks. – Riley – 9 years ago

6

2sable, 24 11 bytes

>G')Ç>çJN×,

Try it online!

And no sign of any asterisks! Golfed from 24 to 11 thanks to @Emigna.

Explanation:

>G')Ç>çJN×,
>            Push input+1
 G           For N in range (1,input+1)
  ')Ç>çJ     Push '*' by getting ascii code for ')' and adding 1
        Nx,  Print '*' repeated N times

Geno Racklin Asher

Posted 9 years ago

Reputation: 466

1A few tips. õVYI doesn't affect your code in any way and can be removed. 1+ is the same as >. If you create the asterisk in the loop you can also remove UX. Using × instead of the inner loop saves even more bytes. Without changing method you can get this down to 11 bytes or less. – Emigna – 9 years ago

1Nice! I'll edit soon – Geno Racklin Asher – 9 years ago

Could you add an explanation? – Buffer Over Read – 9 years ago

Wonderful code, congrats on getting the bounty! The community bot seems to have awarded only 25 and not the original 50 I think because I forgot to award the bounty before the deadline, sorry for that. – Buffer Over Read – 9 years ago

1Don't worry about it. Just glad to reach the 100-rep mark. @TheBitByte – Geno Racklin Asher – 9 years ago

6

Dyalog APL, 8 bytes

↑'*'⍴⍨¨⍳

matrify the list consisting of

'*' the string "*"

⍴⍨ reshaped by

¨ each of

the integers 1 through the argument.

TryAPL online!

Adám

Posted 9 years ago

Reputation: 37 779

Looks like 8 bytes to me. – Erik the Outgolfer – 8 years ago

1if can be a single byte: (,⍕⊢)⌸⍳ – ngn – 8 years ago

@ngn That is very clever! Post it as your own. You may indeed count it as a single byte it you write 7 bytes<sup>SBCS</sup>. – Adám – 8 years ago

5

V, 8 bytes

Àé*hòlÄx

Try it online!

James

Posted 9 years ago

Reputation: 54 537

Oh, yes, Àé hòlÄ! – Jonathan Allan – 9 years ago

2@JonathanAllan Hey, at least it's more readable than Jelly. (To me) ;) – James – 9 years ago

Jelly's code page is, pretty well organised I think. Check out the overhal of the wiki's Atoms page made recently by Lynn.

– Jonathan Allan – 9 years ago

3@JonathanAllan Yeah, I'd believe it. It may not look like it, but V's mnemonics are well organized because of the keys you use to type them in vim. So my solution in vim-key lingo is <M-@><M-i>*h<M-r>l<M-D>x (m stands for meta, which means alt). All of those are pretty good mnemonics for what the command does. – James – 9 years ago

5

JavaScript (ES6), 34 bytes

f=x=>x?f(x-1)+`
`+'*'.repeat(x):''

Huntro

Posted 9 years ago

Reputation: 459

5

Perl 5, 22 20 bytes

say"*"x$_ for 1..pop

Run it with the -E switch to get say.

$ perl -E 'say"*"x$_ for 1..pop' 5
*
**
***
****
*****

Written out as a full program it would look like this:

use strict;
use feature 'say';

# get the argument
my $limit = pop @ARGV;

foreach my $i (1 .. $limit) { 
    say "*" x $i; 
}
  • shift and pop implicitly work on @ARGV (the list of arguments) outside of subs
  • .. is the range operator
  • say includes a newline
  • x is an operator to repeat strings and is explained in perlop

simbabque

Posted 9 years ago

Reputation: 487

Not sure if I need extra bytes for the command line switch. – simbabque – 9 years ago

I believe the -E flag counts as 1 extra byte. – ETHproductions – 9 years ago

What about taking the number as input instead of parameter? perl -E 'say"*"x$_ for 1..<>' <<< 5 – manatwork – 9 years ago

@manatwork yeah that would work. I'm not good at counting though. Not sure if that's allowed. – simbabque – 9 years ago

1-E is free (as it replaces -e which would be needed anyway). If you really want to take the number from the command line (why not, even if <> is 1 byte shorter, and allowed), you should use pop instead of shift (2 bytes shorter)! Anyway, welcome on PPCG, happy to see you golfing! – Dada – 9 years ago

@simbabque, of course is allowed. You can take even implicit input with -n or -p (possibly combined with -a and -F), just that those are counted. So perl -nE 'say"*"x$_ for 1..$_' <<< 5 is also acceptable just unnecessary long. – manatwork – 9 years ago

5

Perl 6, 23 bytes

{.put for [\~] '*'xx$_}

( If the output is allowed to be a list of "lines" without newlines .put for  can be removed )

Explanation:

# bare block lambda with implicit parameter 「$_」
{
  .put            # print with trailing newline
    for           # for every one of the following
      [\~]        # produce using concatenation operator
        '*' xx $_ # list repeat '*' by the input
}

( See documentation for produce if you don't understand what [\~] ... is doing )

Brad Gilbert b2gills

Posted 9 years ago

Reputation: 12 713

5

Perl, 19 bytes

-4 bytes thanks to @Ton Hospel and his rework of the solution!

eval"s//*/;say;"x<>

Needs free -E (or -M5.010) flag to run. Takes a number from input :

perl -E 'eval"s//*/;say;"x<>' <<< "5"

Dada

Posted 9 years ago

Reputation: 8 279

1You can make eval the same length as the for solution (using <> instead of pop) with eval"s//*/;say;"x<> – Ton Hospel – 9 years ago

@TonHospel Ineed, nice! thanks! – Dada – 9 years ago

5

J, 11 8 bytes

Saved 3 bytes thanks to miles!

]\@#&'*'

Here is a decomposition:

(]\@#&'*') x
x (]\@#) '*'
]\ (x # '*')

Now, this last one reads as "the prefixes (]\) of the string consisting of x copies of '*'". Observe:

   5 ]\@# '*'
*
**
***
****
*****
   ]\ 5# '*'
*
**
***
****
*****
   ]\ 5 # '*'
*
**
***
****
*****
   ]\@#&'*' 5
*
**
***
****
*****

Test case

   f =: ]\@#&'*'
   f 3
*
**
***
   f 5
*
**
***
****
*****
   f 1
*
   f 2
*
**
   f &. > ;/1+i.10
+-+--+---+----+-----+------+-------+--------+---------+----------+
|*|* |*  |*   |*    |*     |*      |*       |*        |*         |
| |**|** |**  |**   |**    |**     |**      |**       |**        |
| |  |***|*** |***  |***   |***    |***     |***      |***       |
| |  |   |****|**** |****  |****   |****    |****     |****      |
| |  |   |    |*****|***** |*****  |*****   |*****    |*****     |
| |  |   |    |     |******|****** |******  |******   |******    |
| |  |   |    |     |      |*******|******* |*******  |*******   |
| |  |   |    |     |      |       |********|******** |********  |
| |  |   |    |     |      |       |        |*********|********* |
| |  |   |    |     |      |       |        |         |**********|
+-+--+---+----+-----+------+-------+--------+---------+----------+

Older, 11-byte solutions

'*'#~"+1+i.

This is equivalent

'*' #~"0 1 + i.

1 + i. is the range [1, x]. Then, '*' #~"0 applied to this range shapes (element) copies of '*'.

Bonus program:

[:#&'*'\#&1

This is a capped fork #&'*'\ applied to the result of #&1 of the input. #&1 gives an array of x ones, and #&'*'\ shapes '*' to the prefixes of this array.

Test cases

   f1 =: '*'#~"+1+i.
   f2 =: [:#&'*'\#&1
   f1 1
*
   f2 2
*
**
   f1 3
*
**
***
   f2 4
*
**
***
****
   f2 5
*
**
***
****
*****
   f1 5
*
**
***
****
*****
   (f1;f2)3
+---+---+
|*  |*  |
|** |** |
|***|***|
+---+---+
   f1;f2
f1 ; f2
   (f1;f2)5
+-----+-----+
|*    |*    |
|**   |**   |
|***  |***  |
|**** |**** |
|*****|*****|
+-----+-----+
   (f1;f2)10
+----------+----------+
|*         |*         |
|**        |**        |
|***       |***       |
|****      |****      |
|*****     |*****     |
|******    |******    |
|*******   |*******   |
|********  |********  |
|********* |********* |
|**********|**********|
+----------+----------+

Conor O'Brien

Posted 9 years ago

Reputation: 36 228

You could also get the prefixes of the string of n copies of '*' for 8 bytes using ]\@#&'*' – miles – 9 years ago

@miles: and another 9 byte version: '*'"0\@i. – Jonah – 8 years ago

5

C, 47 46 45 43 bytes

Takes input from the command line

f(n){for(n&&f(n-1);~n;putchar(n--?42:10));}

Basically if n is not 0 recurse on n-1. at the top of the recursion where n is 0 it just prints a newline, the for loop terminates when n is -1 or ~n is zero, otherwise it prints ASCII 42 which is '*'. Try it on ideone

C++ 58 Bytes + 19 for including iostream is 77

#include<iostream>
int f(int n){for(n&&f(n-1);~n;std::cout<<(n--?"*":"\n"));}

main(c,v)char**v;
{
    f(atoi(v[1]));
}

a.exe 3
*
**
***

cleblanc

Posted 9 years ago

Reputation: 3 360

To me seems to work with &&: n?f(n-1):0n&&f(n-1). – manatwork – 9 years ago

@manatwork Thanks bud. saving another byte – cleblanc – 9 years ago

In ideone the print of 2 triangle show at the end there is one '\n' more: * **


**



***** I say the case 0 the case end of revursion, print one \n more – RosLuP – 9 years ago

@RosLup Yes it's printing a leading and a trailing newline. I think the OP said that was OK in his comments. – cleblanc – 9 years ago

5

Vim, 22, 18 keystrokes

O <esc>J:h r<cr>lyEZZ<C-v>{@"

Huge credit to @Udioica for coming up with an awesome vim answer that I expanded on. This answer does not contain any asterisks, in hopes of winning the bounty.

Explanation:

Input is typed before the rest of the program. Udioica came up with this awesome trick. Typing <n>O <esc> will create a pyramid of spaces and one empty line, as long as you have :set autoindent enabled. This option comes on by default in vim 8 and neovim, though not older versions of vim. Since this also creates an extra line, we use J to join this line with the next one, which effectively just removes the line below us.

Now at this point, we need to replace all of these spaces with asterisks. If I was not worried about using asterisks in my code, I would just visually select the whole thing <C-v>{ and type r*, which replaces each character of the selection with an asterisk. But I can't do that.

So we open up the help pages to :h r. The interesting thing about this is that in the vim-window, this page is displayed as:

                            r
r{char}         Replace the character under the cursor with {char}.
                ...

With the cursor on the first 'r'. However, the file itself actually contains this text:

                            *r*
r{char}         Replace the character under the cursor with {char}.
                ...

Pretty convenient. So we move over one character with l, and yank the text r* with yE ([y]ank to the [E]nd of this word).

To close this buffer, we use the shortcut to save a file ZZ. Now, we visually select our spaces, and run the yanked text as if we had typed it by doing @". This works because "@" runs the following register as vim-keystrokes, and " is the default register for yanking.

James

Posted 9 years ago

Reputation: 54 537

Care to explain how it works? – corvus_192 – 9 years ago

@corvus_192 I have added a more extensive explanation, as well as golfing some more off. – James – 9 years ago

Shouldn't the size of the data file be added to the byte count? – aross – 9 years ago

@aross the size of the help file? No, because this file is installed alongside vim, and is a default feature. – James – 9 years ago

4

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]

FlipTack

Posted 9 years ago

Reputation: 13 242

4

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

Shaun Bebbers

Posted 9 years ago

Reputation: 1 814

4

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

Thiago Oleinik

Posted 9 years ago

Reputation: 341

4

Retina, 14 bytes

Byte count assumes ISO 8859-1 encoding.

.+
$**
.
$`$&¶

Try it online!

Explanation

.+
$**

Turn the input N into N asterisks.

.
$`$&¶

Replace each asterisk with everything up to and including that asterisk (this is the $`$&) and a linefeed (this the ).

Martin Ender

Posted 9 years ago

Reputation: 184 808

4

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 '*'

Kevin Cruijssen

Posted 9 years ago

Reputation: 67 575

1I beat you by 1 byte – Numberknot – 9 years ago

1@Numberknot 2 bytes, since you can golf it by 1 more. :) – Kevin Cruijssen – 9 years ago

4

MATL, 9 8 bytes

1 byte saved thanks to @Luis

:"42@Y"c

Try it Online

Suever

Posted 9 years ago

Reputation: 10 257

4

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

Luis Mendo

Posted 9 years ago

Reputation: 87 464

You can use map on number without taking the range to save another byte.

– Linus – 9 years ago

4

Cubix, 22 bytes

?(.;I:^;/-.@o;(!\>'*oN

Test it online! Outputs a trailing newline.

At first I wasn't sure I could get this to fit on a 2-cube, but in the end it worked out fine:

    ? (
    . ;
I : ^ ; / - . @
o ; ( ! \ > ' *
    o N
    . .

I'll add an explanation when I have time, hopefully later today.

ETHproductions

Posted 9 years ago

Reputation: 47 880

Explanation anytime soon? :P – FlipTack – 8 years ago

3

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)^

Esolanging Fruit

Posted 9 years ago

Reputation: 13 542

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.) – Ørjan Johansen – 8 years ago

@ØrjanJohansen Thanks, edited. – Esolanging Fruit – 8 years ago

3

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.

JayCe

Posted 9 years ago

Reputation: 2 655

3

W n, 6 4 bytes

'**M

Explanation

   M           % Map every item in the implicit input with...
               % (There's an implicit range from 1)
'**            % asterisks input times

n % Join the result with a (n)ewline

How do I use the n flag?

... W.py filename.w [input-list] n

user85052

Posted 9 years ago

Reputation:

3

Batch, 69 bytes

@set s=
@for /l %%i in (1,1,%1)do @call set s=*%%s%%&call echo %%s%%

Neil

Posted 9 years ago

Reputation: 95 035

3

Ruby, 26 bytes

->n{s='';n.times{p s+=?*}}

Lee W

Posted 9 years ago

Reputation: 521

2p will surround each line with double-quotes (because it calls inspect on its arguments). I can't speak for OP, but I suspect this disqualifies your answer. – Jordan – 9 years ago

3

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
]

Sean McBane

Posted 9 years ago

Reputation: 71

IIRC you can take a character as input and use its ascii code – acrolith – 9 years ago

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. – Sean McBane – 9 years ago

Yes, but your code would be smaller and I've seen other BF answers using that. – acrolith – 9 years ago

Where can I find the official rules for code golf on this site? – Sean McBane – 9 years ago

How is it that my Clojure solution is exactly as long as a BrainFuck answer? -_- – Carcigenicate – 9 years ago

3

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 '*'

ASCII-only

Posted 9 years ago

Reputation: 4 687

3

Lua, 36 bytes

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

Takes input from the command line.

IDid

Posted 9 years ago

Reputation: 101

How exactly you run it? I always get only an error: “lua5.3: IDid.lua:1: 'for' limit must be a number”. – manatwork – 9 years ago

@manatwork You can run it using e.g. lua IDid.lua 5 for 5 lines. – IDid – 9 years ago

Indeed. Thanks. No idea what I combined earlier. (Was before coffee…) – manatwork – 9 years ago

3

TI-Basic, 28 22 bytes

Prompt A
"*
For(B,1,A
Disp Ans
Ans+"*
End

Timtech

Posted 9 years ago

Reputation: 12 038

Prompt A "* For(B,1,A Disp Ans Ans+"* End for 22 bytes – pizzapants184 – 8 years ago

Wow, I should have thought of that. Thanks @pizzapants184 – Timtech – 8 years ago

3

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.

xnor

Posted 9 years ago

Reputation: 115 687

3

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!

ATaco

Posted 9 years ago

Reputation: 7 898

Not sure if checking program length is borderline abusing the bounty rules or not... – Buffer Over Read – 9 years ago

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. – ATaco – 9 years ago

Okay, I guess I'll get this one pass. Also, grabbing the asterisk from some predefined constant isn't allowed anyways. – Buffer Over Read – 9 years ago

3

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.

Gabriel Benamy

Posted 9 years ago

Reputation: 2 827

Very awesome way of doing it, wow. – Buffer Over Read – 9 years ago

3

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

SuperJedi224

Posted 9 years ago

Reputation: 11 342

3

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)]

James Murphy

Posted 9 years ago

Reputation: 267

Why not just use range? – FlipTack – 9 years ago

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. – James Murphy – 9 years ago

1I know the difference. But this is code-golf :P – FlipTack – 9 years ago

2

Common Lisp, SBCL, 69 66 61 45 44 41 bytes

full program:

(dotimes(i(read))(format t"~v{*~}*
"i 1))

Explanation

(dotimes(i(read)) <-- loop from i=0 to i=INPUT-1
(format t"~v{*~}*
"i 1)) <-- loop, displaying i+1 asterisks per line

Ideas for improvement are welcomed.

user65167

Posted 9 years ago

Reputation:

2

SmileBASIC, 30 bytes

INPUT N
FOR I=1TO N?"*"*I
NEXT

12Me21

Posted 9 years ago

Reputation: 6 110

2

Haskell 36 Bytes

Here is a version using map.

f="*":map('*':)f;g=unlines.(`take`f)

Input g 10 Output "*\n**\n***\n****\n*****\n******\n*******\n********\n*********\n**********\n"

Alternatives of interest might be:

38 Bytes

g n=id=<<scanl(\x y->'*':x)"*\n"[2..n]

38 Bytes

f="*\n":map('*':)f;g n=id=<<(n`take`f)

36

g n=id=<<(take n$iterate('*':)"*\n")

brander

Posted 9 years ago

Reputation: 111

Anonymous functions are allowed, so you don't need the g=. – Laikoni – 9 years ago

2

k, 18 bytes

{-1@(1+!x)#\:"*";}

Explanation:

-1@ // prints to console

1+!x //returns list from 1 to x (implicit input)

#\:  //for each item in the prefixed list, "take" this many

"*" //asterisk string

Paul Kerrigan

Posted 9 years ago

Reputation: 189

1@ isn't necessary, and you can use ' instead of : for -2 bytes {-1(1+!x)#'"*";} – Thaufeki – 7 years ago

2

Perl 6, 17 bytes

put(\*x++$)xx get

Full program that prints to stdout.
How it works:

    \*             # a Capture object that stringifies to the asterisk,
      x            # string-repeated by
       ++$         # a counter that starts at 1,
put(      )        # and printed followed by a newline.
           xx get  # Do all of that n times.

Invokes the put statement n times, each time printing the asterisk repeated by the counter variable ++$.


Perl 6, 21 bytes

{.put for \*Xx 1..$_}

A lambda that prints to stdout.
How it works:

{                   }  # A lambda.
          \*           # A Capture object that stringifies to the asterisk.
               1..$_   # Range from 1 to n.
            X          # Cartesian product of the two,
             x         # with the string repetition operator applied to each result.
 .put for              # Iterate over the strings, and print each followed by a newline.

smls

Posted 9 years ago

Reputation: 4 352

2

Bash + Unix utilities, 26 bytes

seq -f10^%f-1 $1|bc|tr 9 *

Output to stderr should be ignored.

Try it online!

The code above works on TIO since the working directory there has no visible files. If this needs to run in a directory that contains a visible file, change * to \* at the cost of one byte (27 bytes):

seq -f10^%f-1 $1|bc|tr 9 \*

Mitchell Spector

Posted 9 years ago

Reputation: 3 392

2

Japt -R, 8 4 bytes

õ_î*

Try it online!

4-byte alternative:

°Tî*

Try it online

Oliver

Posted 9 years ago

Reputation: 7 160

1You know, instead of adding a newline to every line, joining with spaces and trimming, you could just join with newlines ;-) – ETHproductions – 9 years ago

Could you use this 5 byte version?

– Shaggy – 8 years ago

2

Terrapin logo, 67 bytes

to a :a
make "b 1 repeat :a[repeat :b[type "*]make "b b+1 pr "]
end

Adrian Zhang

Posted 9 years ago

Reputation: 199

2

k, 16 12 bytes

4 bytes removed thanks to ngn! :)

{`0:,\x#"*"}

{          } /function(x)
      x#"*"  /reshape "*" by x
    ,\       /scan concatenation through the list
 `0:         /print line by line

zgrep

Posted 9 years ago

Reputation: 1 291

1(1+!x)#'"*" -> ,\x#"*" – ngn – 8 years ago

2

K, 16 Bytes

 {-1(1+!x)#'"*"};

  {-1(1+!x)#'"*"}10;
* 
**
***
****
*****
******
*******
********
*********
**********

EDIT BELOW - adding explanation)

/Code     ---> explanation (pretend x is 3)
1+!x      ---> Numbers from 1 to 3
1 2 3#"*" ---> Take left many items of right ==> ("*";"**";"***")
-1x       ---> Print x to the console, if x is a list, each item is printed to a new line

example(notice the -1 printed at the bottom). 
     -1("*";"**";"***")
     *
     **
     ***
     -1
To silence the output(-1), put a semicolon after the expression e.g.
-1("Hello");
Hello

Chromozorz

Posted 9 years ago

Reputation: 338

2

Röda 0.12, 30 29 bytes, non-competing

h i{seq 1,i|{|j|print"*"*j}_}

This is my first try in this scripting language created by fergusq :D

This is a function. To run, use this:

h i{seq 1,i|{|j|print"*"*j}_}

main {
  h(5)
}

Ungolfed

h i{                         /* Define a function h with parameter i */
   seq 1,i                   /* Generate a sequence of numbers from 1 to i */
          |{             }_  /*  and pipe it to a for-loop */
            |j|              /*  where j is the number in the sequence*/
               print"*"*j    /*  and print an asterisk duplicated j times*/
}

user41805

Posted 9 years ago

Reputation: 16 320

The ; after the anonymous function parameter list is not actually required in Röda 0.12. It's a bug in the interpreter, but since you've specified the answer to be 0.12, I think you can remove it. I have been thinking that I may let the bug be, as its a handy feature in code golf, but haven't decided anything yet. – fergusq – 9 years ago

@fergusq Thanks for the tip! "It's not a bug, it's a feature!" – user41805 – 9 years ago

2

Excel VBA, 32 Bytes

Anonymous VBE immediate window function that takes input from range A1 and outputs to the VBE immediate window.

For i=1To[A1]:?String(i,42):Next

Taylor Scott

Posted 9 years ago

Reputation: 6 709

2

SNOBOL4 (CSNOBOL4), 59 52 bytes

	n =input
o	output =o =o '*' lt(size(o),n) :s(o)
end

Try it online!

Giuseppe

Posted 9 years ago

Reputation: 21 077

2

APL (Dyalog Unicode), 7 bytesSBCS

(,⍕⊢)⌸⍳

Try it online!

ngn

Posted 9 years ago

Reputation: 11 449

2

Canvas, 3 bytes

*×]

Try it here!

Explanation:

  *×]  full program
{  ]  map over [1..input]
  *×      repeat by *

dzaima

Posted 9 years ago

Reputation: 19 048

2

Wren, 41 bytes

Fn.new{|i|(1..i).map{|n|"*"*n}.join("
")}

Try it online!

Explanation

Fn.new{|i|                             // New function with the parameter i
          (1..i)                       // Generate a range from 1 to i
                .map{|n|"*"*n}         // Replace the numbers with asterisks
                              .join("
")}                                    // Join with newline

user85052

Posted 9 years ago

Reputation:

2

MathGolf, 4 bytes

╒⌂*n

Try it online or verify some more test cases.

Explanation:

╒     # Push a list in the range [1, (implicit) input]
 ⌂    # Builtin for the asterisk character "*"
  *   # Map each value to that amount of asterisk characters (similar as in Python)
   n  # And join this list of strings by newlines
      # (after which the entire stack joined together is output implicitly as result)

Kevin Cruijssen

Posted 9 years ago

Reputation: 67 575

2

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:

*
**
***
****
*****

rnso

Posted 9 years ago

Reputation: 1 635

2

QBIC, 16 bytes

:#*|[1,a|B=B+A?B

Explanation:

:         Gets a cmd line param as number called 'a'
#*|       Define A$ as '*'
[1,a|     FOR b = 1 to a
B=B+A     Extend B$ with another astrix
?B        Print B$
<FOR LOOP implicitly closed>

QBIC's seen a few updates since this answer was posted. This could now be done with these 12 bytes:

[:|B=B+@*`?B

steenbergh

Posted 9 years ago

Reputation: 7 772

2

PHP, 43 34 31 28 bytes

Note: uses IBM 850 encoding (old favorite reinvented recently)

for(;$argn--;)echo$o.=~ı,~§;

Run like this:

echo 5 | php -nR 'for(;$argn--;)echo$o.=~ı,~§;';echo
> *
> **
> ***
> ****
> *****

Explanation

Iterates from N down to 0. Add an asterisk to $o for each iteration, then outputs $o and a newline.

Tweaks

  • Add an asterisk to $o for each iteration, and then output $o. Saves 9 bytes
  • Combined adding an asterisk to $o with outputting, saves 3 bytes
  • Saved 3 bytes by using $argn

aross

Posted 9 years ago

Reputation: 1 583

@TheBitByte, does my answer qualify for your bounty? It yields an asterisk by binary negation of ı (in IBM-850 encoding, as noted) – aross – 9 years ago

Well, as long as it's an actual asterisk, then fine, it does qualify, however it is longer than some other bounty answers here. – Buffer Over Read – 9 years ago

2

Pyke, 6 bytes

Voh\**

Try it here!

Blue

Posted 9 years ago

Reputation: 26 661

2

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
{}

James

Posted 9 years ago

Reputation: 54 537

2

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.

Mego

Posted 9 years ago

Reputation: 32 998

2

Pyth, 10 8 Bytes

thanks to Jakube for helping me shave off the extra 2 bytes!

VQ*Np"*"

Try it

Connor D

Posted 9 years ago

Reputation: 81

FNU is the same thing as V. And you don't need that p, printing is implicit. – Jakube – 9 years ago

without the p the code doesn't execute properly. It would print one less level than it should. – Connor D – 9 years ago

2

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]

Level River St

Posted 9 years ago

Reputation: 22 049

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. – m-chrzan – 9 years ago

2

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>

ATaco

Posted 9 years ago

Reputation: 7 898

2

Groovy, 27 characters

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

Sample run:

groovy:000> ({1.upto(it){println"*"*it}})(5)
*
**
***
****
*****
===> null

manatwork

Posted 9 years ago

Reputation: 17 865

{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. – Magic Octopus Urn – 9 years ago

1

@carusocomputing, yepp, I also usually forget about .upto, but this time IMP1's Ruby answer reminded it.

– manatwork – 9 years ago

2

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

manatwork

Posted 9 years ago

Reputation: 17 865

2

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;}

416E64726577

Posted 9 years ago

Reputation: 123

2

GameMaker Language, 68 bytes

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

Timtech

Posted 9 years ago

Reputation: 12 038

2

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.

Sijmen Schoon

Posted 9 years ago

Reputation: 21

2

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 !

adrianmp

Posted 9 years ago

Reputation: 1 592

2

Since the course is taught in C++, I'm eager to see solutions in C++.

C++, 123 bytes, Non-competing

(the joke here is to deliver a 'pure' c++ answer)

#include<string>
class X:public std::string{public:X(int i):std::string(i*(i+1)/2,'*'){for(;i--;)insert(i*(i+1)/2,"\n");}};

Test

user60119

Posted 9 years ago

Reputation:

2

Brainfuck, 129 bytes

I know there's already a shorter answer in brainfuck, however I wanted to create a program which could handle a multi-digit number input rather than either a single-digit input or a single ascii character input unlike the previous one posted.

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

This is my first ever brainfuck program and it will work for any input between 0 and the maximum size of a single cell (traditionally 8 bits or 255) entered using the characters '0' to '9' (corresponding to ascii-values 048-057)

Explanation

The first part of this program, ,[>+++[->++++[-<<---->>]<]+>,], takes the input numbers as char values and removes 48 from each to make them equal to the numbers 0 to 9 rather than the char values of the numbers 0 to 9. It stores these in separate cells with a 1 in between each of them so that the start and end points can be found again.

The second part, <-<<[<<]>>[<[->>++++++++++<<]>>>], consolidates the separate values into one cell. This is why the maximum size of a cell controls how high a number can be.

The third section, +>>++++++++++>>++++++[-<+++++++>]<<<<<, is used to set up the other cells needed: one with the number of asterisks per line, one with the code for a linefeed and one with the code for an asterisk. There is also a blank cell left for working with later.

The remainder of the code, [>[->+>>.<<<]>>.<[-<+>]<+<-], is used to:

  1. Output as many asterisks as necessary
  2. Output a linefeed
  3. Reset the value of the cell controlling the asterisks
  4. Increment the control cell
  5. Decrement the cell with the number until it equals 0

Anonymous No Lifer

Posted 9 years ago

Reputation: 311

2

05AB1E, 11 bytes

'*×.pD¦`r`»

Try it online!

Explanation: (Prints hourglass)

                  Implicit input - 5
'*                Asterisk character - stack = '*'
  ×               Repeat input times - stack = '*****'
   .p             Get prefixes       - stack = ['*', '**', '***', '****', '*****']
     D            Duplicate last element
                  STACK = ['*', '**', '***', '****', '*****'] , ['*', '**', '***', '****', '*****']
      ¦           Remove first element from final list
                  STACK = ['*', '**', '***', '****', '*****'] , ['**', '***', '****', '*****']
       `r`        Reverse 1 list and flatten both
                  STACK = '*****','****','***','**','*','**','***','****','*****'
          »       Join by newlines and implicitly print

For input 5, prints:

*****
****
***
**
*
**
***
****
*****

Geno Racklin Asher

Posted 9 years ago

Reputation: 466

2

C++ 11, 65 bytes

Not including the include in the byte count.

#include<string>
using S=std::string;S g(int n){return n?g(n-1)+S(n,'*')+'\n':"";}

Usage:

std::cout << g(n) << std::endl;

Karl Napf

Posted 9 years ago

Reputation: 4 131

2

SQL, 153 Bytes

Golfed:

CREATE PROCEDURE P @n INT AS BEGIN DECLARE @a INT;SET @a=0;DECLARE @o VARCHAR(1000);SET @o='*'WHILE @a<@n BEGIN PRINT @o;SET @o=@o+'*'SET @a=@a+1;END;END

Ungolfed:

CREATE PROCEDURE P
@n INT 
AS 
BEGIN 
DECLARE @a INT;
SET @a=0;
DECLARE @o VARCHAR(1000);
SET @o='*'
WHILE @a<@n
    BEGIN 
    PRINT @o;
    SET @o=@o+'*'
    SET @a=@a+1;
END;
END

Testing:

EXEC P '6'

Output:

*
**
***
****
*****
******

Pete Arden

Posted 9 years ago

Reputation: 1 151

1Wow, that's awesome! :-) – Sickboy – 9 years ago

@Sickboy thanks! :) My language of choice is normally C#, but someone beat me to it! :) – Pete Arden – 9 years ago

just @ is also a legal variable name in SQL, might save a couple of bytes there, and you can set the variable values directly in the DECLARE like so DECLARE @a INT=0 and a lot of those ; are unnecessary – grabthefish – 9 years ago

also VARCHAR(MAX) is 1 shorter – grabthefish – 9 years ago

2

Dip, 6 5 bytes

`**En

-1 byte thanks to Oliver

Explanation:

`**    Push "*" repeated input times
   E   Prefixes
    n  Join by newlines

acrolith

Posted 9 years ago

Reputation: 3 728

5-byte version: ``**En` – Oliver Ni – 9 years ago

2

Crystal, 31 bytes

n=5;(1..n).each{|x|puts "*"*x}

Output:

*
**
***
****
*****

Really demonstrates the beauty of Crystal/Ruby. n is the integer input, (1..n) is an inclusive range from 1 to n ([1, n]). .each is a method on Range that runs the provided block for every integer in the range.

Zatherz

Posted 9 years ago

Reputation: 111

2

python3, 58 57 bytes

print('\n'.join(['*'*(p+1)for p in range(int(input()))]))

Ungolfed:

rownums = int(input())
output = []
for i in range(rownums):
    currrow = "*" * (i+1) # 'i' * 5 == 'iiiii'
    output.append(currrow)
print('\n'.join(output))

Elronnd

Posted 9 years ago

Reputation: 101

2

C, 88 bytes / 53 bytes

Using C89.

g(a){a&&g(a-1);a<2||puts("");while(a--)putchar('*');}main(int a,char**v){g(atoi(v[1]));}

With whitespace for clarity:

g(a) {
    a && g(a-1);
    a<2 || puts("");
    while (a--) putchar('*');
}
main(int a, char** v) {
    g(atoi(v[1]));
}

Without main, this function is 53 bytes:

g(a){a&&g(a-1);a<2||puts("");while(a--)putchar('*');}

user61383

Posted 9 years ago

Reputation:

1

><>, 47 bytes

<v[1:$-1;!?:$+10
0\:&
$>:@=?v1+&:&"*"o
0f]oa~<.

Try it here!

This was fun to write, though a bit more bytes than I expected.

redstarcoder

Posted 9 years ago

Reputation: 1 771

1

Sinclair ZX81/Timex TS1000/1500, 117 bytes (listing)

1 PRINT "NUMBER OF * TO SHOW?"
2 INPUT A
3 IF A<1 THEN STOP
4 LET J=A/A
5 FOR I=1 TO A
6 FOR X=1 TO J
7 PRINT "*";
8 NEXT X
9 LET J=J+1
10 PRINT
11 NEXT I

Note that because the screen scroll isn't handled in this program listing, you may only enter a number between 0 and 22 because as soon as the ZX81 hits the bottom of the screen it will halt the program. You can see the missing * by using CONT when this happens, but also note that the ZX81 only has 32 columns text by default in BASIC.

Shaun Bebbers

Posted 9 years ago

Reputation: 1 814

To save actual (system) bytes, you may amend the following lines: 3 IF A<CODE "{GRAPHICS ON}{SHIFT}1{SHIFT OFF}{GRAPHICS OFF}" 5 FOR I=PI/PI TO A 6 FOR X=PI/PI TO J 9 LET J=J+PI/PI – Shaun Bebbers – 9 years ago

1

SQL, 80 bytes

DECLARE @i INT=1,@ INT=5WHILE @i<>@ BEGIN PRINT REPLICATE('*',@i)SET @i=@i+1 END

ungolfed:

DECLARE @index INT=1, 
        @rows INT=5

WHILE @index<>@rows 
BEGIN 
    PRINT REPLICATE('*',@index)
    SET @index=@index+1 
END

grabthefish

Posted 9 years ago

Reputation: 161

1

Rebol, 32 bytes

loop do input[print append{}"*"]

Ungolfed:

loop do input [
    print append {} "*"
]

draegtun

Posted 9 years ago

Reputation: 1 592

1

AutoHotkey, 28 bytes

Loop,%1%
Send,{* %A_Index%}`n

%1% is the first argument passed in
%A_Index% is the current iteration in the loop
Send sends a keystroke multiple times if it's followed by a number

Engineer Toast

Posted 9 years ago

Reputation: 5 769

1

dc, 33 bytes

?sa0[1+d1F6r^3C*1EF/PAPdla>x]dsxx

Input on stdin, output on stdout.

Try it online!

Mitchell Spector

Posted 9 years ago

Reputation: 3 392

1

Forte, 101 bytes

1INPUT0
2LET4=(0*(0+1))*5
4END
6PUT42:LET7=6+1
7LET6=6+10
8PUT10:LET9=((9+9)+14)-3:LET3=8+5
3LET8=9-1

Try it online!

I've been wanting to try Forte for a while, and this seemed like a fine challenge for it. It was quite an effort writing the program, then golfing it and making it fit in one-digit numbered lines. It was also quite fun :) Kudos to ais523 for inventing this and many more incredible languages.

Since I'm in the mood I'll write an explanation in details, covering also the basis of the language.

Explanation

First, a very brief introduction for those who don't know this language, you can find the full specification and guide on its esolang page.

The syntax of Forte is similar BASIC, with line numbers prepended to each line, only that in Forte you dont GOTO 10, you make 10 come to you!

With the command LET, you can assign a number to... another number. If the command LET 10=20 is executed, from now on every time the number 10 is referenced, directly or indirectly (5+5 counts too), it is replaced by 20 instead. This affects line numbers too, so if we were on line 19 when executing that instruction, the next line to be executed will be our old line 10, now line 20.

Now, the actual code (with spaces added for clarity):

1 INPUT 0

This is practically LET 0=<a number taken from stdin>, in this program 0 is used like a variable, and only in line number 2

2 LET 4=(0*(0+1))*5
4 END

Line 4 is the one that terminates the program, so we want to put it at the position where we are done printing asterisks. How many of them do we need to print, though? As fitting for a "draw a triangle" challenge, the answer is given by triangular numbers!

The formula to calculate the nth triangular number is n*(n+1)/2. We will print an asterisk every 10 lines, so we multiply it by 10 and get n*(n+1)*5. Use 0 instead of n, add parentheses for every operation (always mandatory in Forte), and you get line 2.

6 PUT 42:LET 7=6+1
7 LET 6=6+10

Here we print the asterisks. The ASCII code for * is 42, so you get what PUT 42 does. The colon separates multiple instructions on the same line, so we then execute LET 7=6+1. What use do we have in redefining 7 as 6+1? Isn't it the same thing? Let's see what happens next.

Line 7 redefines 6 as 6+10, so 16. Ignoring for a moment the rest of the code, this means that when we reach line 16 we will print another asterisk, and then redefine 7 as 6+1. But now 6 is 16, so we are redefining it as 16+1! Line 7 is now line 17 and is the next one to be executed, changing 6 to 6+10, which means changing 16 to 16+10, so on line 26 we will print another asterisk, and so on.

Since in Forte a line cannot change its own number, this is the simplest structure for a loop, two lines changing each other's numbers repeatedly. I know this can be quite confusing, but that's kind of the point of the whole language ;)

8 PUT 10:LET 9=((9+9)+14)-3:LET 3=8+5
3 LET 8=9-1

Ok, that line 3 put here may seem out of place, but in Forte line order doesn't matter, only line numbering. I've chosen to put this line at the end because this pair of lines forms again a cycle, redefining each other's numbers, so it's easier to see them together. Moreover, the first time line 3 is executed (when 3 is still equal to 3 and nothing else), it has no effect on the program, redefining 8 as 8.

As you probably have guessed PUT 10 prints a newline, then the hard part comes. We want each line to have one more asterisk than the one before, so to know where to put the next newline we need to know where the previous one was. To do this, we use another "variable": the number 9. In practice, when we are about to print a newline on line 8, line 3 will be positioned (near) where the previous newline was printed, we'll use it to calculate where the next newline must be printed and move 9 (near) there. (Remember that line 8 can't move itself). Then we move line 3 a bit further than the current position, and use it to move line 8 to our 9.

These three numbers (3,8, and 9) were chosen in order not to conflict with any other redefinition of a number, and to be easy to use together (since neither 5 nor 1 will ever be redefined by this program we can do LET 3=8+5 and LET 8=9-1).

All of these numbers will always be redefined as themselves+10n. This means that 8 will only ever be redefined to numbers ending with an 8 (28,58,98...). This same property is valid for any other number redefinintion in this program (except 0), because this helped greatly my reasoning while writing the code (if you are crazy enough you can try to golf some bytes by using a smaller step, but I doubt there is much room for golfing without completely changing approach).

So, the actual difficult part of this program: LET 9=((9+9)+14)-3. This operation can be better explained if expanded to LET 9=(9+(9-(3-4)))+10, where 4 and 10 represent their respective actual numerical values (in the code they are grouped as 14, 4 wouldn't actually be usable because it was redefined in line 2). As we said before 3 is still placed near the previous newline; we subtract 4 from it to get the previous position of 9 (if 3 is 63, our previous 9 was 59), then we compute the difference between the current and the previous 9 to know how many program-lines have passed since the last newline was printed. We add this value to the current 9, plus 10 because the next time we will want to print one more asterisk. Our 9 is now where we want to print the next newline, so we move 3 to the current position, it will then move 8 to where it's needed, just before 9.

Phew, that was long. And hard. No dirty jokes, please

Leo

Posted 9 years ago

Reputation: 8 482

1

Perl 6 (27)

{.say for '*' <<x<<(1..$_)}

bb94

Posted 9 years ago

Reputation: 1 831

1

tcl, 39

time {puts [string repe * [incr i]]} $n

demo

tcl, 46

while {[incr i]<=$n} {puts [string repe * $i]}

demo

sergiol

Posted 9 years ago

Reputation: 3 055

1

JavaScript (ES6), 44 bytes

n=>[...Array(n)].map(_=>s+="*",s="").join`
`

If outputting as an array is permitted then subtract 8 bytes.

n=>[...Array(n)].map(_=>s+="*",s="")

Try it

f=
n=>[...Array(n)].map(_=>s+="*",s="").join`
`
oninput=_=>o.innerText=f(+i.value)
o.innerText=f(i.value=5)
<input id=i min=1 type=number><pre id=o>

Shaggy

Posted 9 years ago

Reputation: 24 623

1

Excel VBA, 37 Bytes

Anonymous VBE immediate window function that takes input from cell [A1] and outputs to range [B:B]

[B1].Resize([A1])="=Rept(""*"",Row())

Taylor Scott

Posted 9 years ago

Reputation: 6 709

1

RProgN 2, 5 bytes

²`**S

Outputs a stack of strings.

Explained

²`**S
²       # Define the function with the next two concepts, `* and * in this case.
    S   # Create a stack from 1 to the input, and execute the previous function on each element.
   *    # Multiply the element by
 `*     # The string "*", which repeats it. Output is implicit.

Try it online!

ATaco

Posted 9 years ago

Reputation: 7 898

1

8th, 38 bytes

Code

( ( "*" . ) swap times cr ) 1 rot loop

SED (Stack Effect Diagram) is: n --

Example

ok> 5 ( ( "*" . ) swap times cr ) 1 rot loop
*
**
***
****
*****

Chaos Manor

Posted 9 years ago

Reputation: 521

1

J, 11 Bytes

$&'*'@>:@i.

Includes trialing spaces on every line.

Explanation:

$&'*'@>:@i.    | Full program
     @  @      | Verb conjunction characters, make sure it isn't executed as a hook
         i.    | Integers 0 to n-1
      >:       | Increment (Integers 1 to n)
$&'*'          | Reshape the array '*' to the size of each item by repeating it cyclically

Note that normally the dyadic ranks of $ are 1 _, so that $&'*' 1 2 3 would create a 1 by 2 by 3 array of '*'s. However, the @ cunjunction ensures that $&'*' is applied to each cell of it's argument.

Bolce Bussiere

Posted 9 years ago

Reputation: 970

Dang, that's a much smarter approach! Good job :) – Bolce Bussiere – 8 years ago

Oh, that's not my post. – FrownyFrog – 8 years ago

1

Japt -R, 4 bytes

õç'*

Try it here

Shaggy

Posted 9 years ago

Reputation: 24 623

1

Julia 0.6, 13 bytes

n->"*".^(1:n)

^ is used for exponentiation and string repeating in Julia. This follows from the choice of '*' for string concatenation, which was chosen over '+' because addition is supposed to be commutative, and string concatenation is not. A function or operator preceded by . is "broadcasted", which in this case mean it is applied elementwise.

Outputs an array of strings. Depending on how the rules are interpreted it may need println.("*".^(1:n)) (23 bytes, meets any interpretation) or display("*".^(1:n)) (22 bytes, prints exact desired output plus an additional line about the array type) or "*".^(1:x).*"\n" (19 bytes, array of strings with newlines). Example of each in TIO.

Try it online!

gggg

Posted 9 years ago

Reputation: 1 715

1

Windows batch, 69 bytes

@set v=
@for /l %%G in (1,1,%1)do @call set v=*%%v%%&call echo %%v%%

Just putting an extra asterisk after each line.

stevefestl

Posted 9 years ago

Reputation: 539

1

brainfuck, 42 bytes

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

Try it online!

Takes the number as the char code of the input. Add two to avoid using negative cells, four to avoid wrapping.

How It Works:

Tape Format:  Input 0 10 * * * *...
++++++++++ Creates the newline cell
<<, Gets input
[ While input
 >>[>] Go to the end of the line of asterisks
 >--[<+>++++++]<- Add an asterisk to the end of the line
 [.<] Print the line including the newline
 <- Subtract one from the input
]

Jo King

Posted 9 years ago

Reputation: 38 234

1

Pyt, 17 bytes

←ř↔0⇹Á`⑴67**Ƈǰƥłŕ

Explanation:

←                             Get input
 ř↔                           Push [input,input-1,...,1] onto stack
   0⇹                         Push 0, and flip the top two items on the stack
     Á                        Push contents of array onto stack
      `         ł             While top of stack is not 0, loop:
       ⑴                     Create an array of 1s with length equal to the top of the stack
         67**                 Multiply each element in the array by 42
             Ƈǰƥ              Convert to ASCII, join, and print; if top of stack is 0, exit loop
                 ŕ            Pop the 0

Try it online!

mudkip201

Posted 9 years ago

Reputation: 833

1

Stax, 4 bytes

m'**

Run and debug it

recursive

Posted 9 years ago

Reputation: 8 616

1

Noether, 14 bytes

I("*"i1+*P?!i)

Try it online

Beta Decay

Posted 9 years ago

Reputation: 21 478

1

GolfScript, 11 bytes

~,{)"*"*n}%

Try it online!

Explanation:

~,                  Create list [0...input-1]
  {      }%         Map over list:
   )"*"*n           Increment, push that many "*"s, push newline

Pseudo Nym

Posted 9 years ago

Reputation: 181

1

Gema, 36 characters

*=@repeat{*;@append{s;\*}@out{$s\n}}

Sample run:

bash-4.3$ gema '*=@repeat{*;@append{s;\*}@out{$s\n}}' <<< 5
*
**
***
****
*****

manatwork

Posted 9 years ago

Reputation: 17 865

1

Forth, 39 bytes

Quite simple, with a couple of nested loops. ASCII 42 is an asterisk.

: f 0 do I -1 do 42 emit loop CR loop ;

Try it online

Prints a trailing newline.

mbomb007

Posted 9 years ago

Reputation: 21 944

1

Bash, 35 characters

for((;i++<$1;));{ s+=\*;echo "$s";}

Sample run:

bash-4.3$ bash draw-an-asterisk-triangle.sh 5
*
**
***
****
*****

manatwork

Posted 9 years ago

Reputation: 17 865

1

C++, 108 chars

#import<iostream>
main(){int n;std::cin>>n;for(int i=1;i<=n;++i){for(int j=i;j--;)std::cout<<"*";puts("");}}

Straightforward.

Try it online

John Doe

Posted 9 years ago

Reputation: 111

Can the < be moved directly next to the #include? (I don't do C++, just a wild guess based on Java knowledge) – Addison Crump – 9 years ago

You're right.__ – John Doe – 9 years ago

1The #include does need to be included in the byte count. – mbomb007 – 9 years ago

Thanks for the C++ solution, but there's a shorter one ;-) – Sickboy – 9 years ago

1

Vitsy, 19 16 bytes

Yeah this needs some reducing. I'm out of practice!

D1H}\[\['*'O]aO]

(implicit input)
D                 Peek n, push n.
 1                Push 1.
  H               Pop x, pop y, push range(x, y)
   }              Reverse, pop n, reverse, push n.
    \[         ]  Pop n, do bracketed items n times.
      \[    ]     Pop n, do bracketed items n times.
        '*'O      Output the character *.
             aO   Output a newline.

Think of it as though I'm iterating through a list (1 through n) and popping out the number of *s according to the currently selected list item.

Explanation soon.

Addison Crump

Posted 9 years ago

Reputation: 10 763

Is implicit input new for vitsy? – Conor O'Brien – 9 years ago

@ConorO'Brien Nope, that's been around since the beginning for numerical inputs through the command line. – Addison Crump – 9 years ago

Huh. My memory fails me, then. – Conor O'Brien – 9 years ago

1

Javascript, 71 bytes 48 Bytes, thanks ETHproductions!

(n,c)=>{while(c<=n)console.log("*".repeat(c++))}

Bladimir Ruiz

Posted 9 years ago

Reputation: 151

Welcome to PPCG! You don't need to call the function, just define it: (n,c)=>{while(c<=n){console.log("*".repeat(c++));}} is a valid entry. Also, you don't need the braces in the while loop, nor the semicolon at the end: (n,c)=>{while(c<=n)console.log("*".repeat(c++))} – ETHproductions – 9 years ago

1

Befunge93, 31 chars (3 spaces, 8 pure directionals)

&>:#v_@
-^  : >$55+,1
,"*"<_^#:-1

Befunge98, 28 chars

&>:#v_@
-^  : >$a,1
1,*'<_^#:-

Demur Rumed

Posted 9 years ago

Reputation: 139

This prints the triangle upside down – Jo King – 8 years ago

The enemy's gate is down – Demur Rumed – 8 years ago

1

Clojure, 59 bytes

#(doseq[m(range 1(inc %))](println(apply str(repeat m\*))))

Basically, just uses doseq to loop over the range, printing the corresponding number of stars.

It's really unfortunate that the shortest way I've been able to repeat a character in Clojure is (apply str (repeat m \*)). That's hardly competitive here. Some good ol' python string multiplication would have been awesome.

Ungolfed:

(defn tri [n]
  (doseq [m (range 1 (inc n))]
    (println (apply str (repeat m \*)))))

Should be fairly self-explanatory.

Carcigenicate

Posted 9 years ago

Reputation: 3 295

1

Jolf, 7 bytes

This time, the builtin didn't let me win. Oh well.

―t0jj'*

Try it here!

Explanation

―t0jj'*
―t0     pattern: left-corner-base triangle
   j     with <input> height
    j    and <input> width.
     '*  comprised of asterisks

Conor O'Brien

Posted 9 years ago

Reputation: 36 228

1

Ruby, 29 bytes

->n{n.times{|i|puts'*'*i+?*}}

Call with ->n{n.times{|i|puts'*'*i+?*}}[number].

dkudriavtsev

Posted 9 years ago

Reputation: 5 781

No need for parenthesis around the proc parameter and is shorter to add a literal character than to add 1 to the multiplier ('*'*(i+1)'*'*i+?*). (BTW, you can call anonymous proc without assigning it to a variable: ->n{n.times{|i|puts'*'*i+?*}}[5].) – manatwork – 9 years ago

1

Java 7,72 70 bytes

Thanks to @kevin for shave it off by 2 bytes.

String f(int n,String s,String c){return n<1?c:f(--n,s+"*",c+s+"\n");}

Output

*
**
***
****
*****
******

Numberknot

Posted 9 years ago

Reputation: 885

Nice approach, +1! Btw, you can golf it by 1 more byte by changing c+= to c+. – Kevin Cruijssen – 9 years ago

I see you've removed both s+= and c+=. I tried the same thing, but now your output is incorrect and contains a leading new line. The s+= should remain and c+= can be c+ for the same output without leading empty line. If OP allows leading newlines then it's of course fine like this. – Kevin Cruijssen – 9 years ago

1

Ruby, 32 bytes

1.upto($*[0].to_i){|i|puts"*"*i}

The $* is an array of arguments.

foo.rb 5 will print the following:

*
**
***
****
*****

IMP1

Posted 9 years ago

Reputation: 510

Unless stated otherwise in the question, the answers should be full programs or functions. In both cases input and output should be handled properly either explicitly by the code itself, or implicitly by the interpreter, if it has such feature. You can not assume your code will find input data in some variable nor to just leave the result in a variable. As it is now, your code is considered a snippet, which is not a valid answer. – manatwork – 9 years ago

ARGV[0]? Sure? Ruby 2.3.1 I use receives command line arguments as String, not Fixnum. – manatwork – 9 years ago

is the output of that okay? It's kinda implicit, but it is returned. – IMP1 – 9 years ago

1

If you ask me, is not valid. Katenkyo suggested in meta to allow such things as he claims Lua programs are able to return string. His suggestion received only 1 upvote and 1 downvote, so there is no consensus on that. In meantime I consider “Programs may output using their exit code... ... if and only if the challenge requires an integer as output, obviously.” relevant with 40 upvotes and 5 downvotes.

– manatwork – 9 years ago

1"Returning a string from a program" doesn't seem well-defined since it's in no way observable. You can fix your program at the cost of a single byte by using $><<"*"*i instead of "*"*i+$/ though. – Martin Ender – 9 years ago

@MartinEnder, $><< appends no implicit newline to the output, so with that would need to keep the +$/ part. Better puts. – manatwork – 9 years ago

@manatwork Yeah sorry, should have been puts. – Martin Ender – 9 years ago

I've gone back to using upto and puts (thankfully still 32 bytes). Is that fine now? – IMP1 – 9 years ago

Yepp, fine. (So fine I already borrowed the .upto idea. ;) )

– manatwork – 9 years ago

1

Excel VBA, 109 bytes

This function returns to cell, requires text wrapping be turned on.

Function a(b)
For i = 1 To b
For c = 1 To i
d = "*" & d
Next c
a = a & d & Chr(10)
d = ""
Next i
End Function

99 Bytes - Alternative that runs as a function but prints to immediate.

Function f(b)
For i = 1 To b
For c = 1 To i
Debug.Print "*";
Next c
Debug.Print
Next i
End Function

94 Bytes - One more that is just a sub with hard coded value, prints to immediate.

Sub k()
r = 5
For i = 1 To r
For c = 1 To i
Debug.Print "*";
Next c
Debug.Print
Next i
End Sub

tjb1

Posted 9 years ago

Reputation: 561

1

PHP, 66 58 bytes

Just a simple loop, really.

I'm new to golfing, so might not be the shortest way.

for($i=fgets(STDIN);$x++<$i;)echo str_repeat("*",$x)."\n";

https://eval.in/658719

Thanks to manatwork for byte-saving.

ʰᵈˑ

Posted 9 years ago

Reputation: 1 426

1No need to explicitly initialize x,soyoucanleavethatoutandmovetheinitializationofi in its place to spare 1 ; separator. And you can combine the loop's test with the loops stepping: for($i=fgets(STDIN);$x++<$i;)echo str_repeat("*",$x)." "; – manatwork – 9 years ago

1

VBA, 84 bytes

taking advantage of recursive coding. it generates x times * as the line/round

Function f(x)
If x<=1 Then f="*" Else f=f(x-1) & vbCrLf & String(x,"*")
End Function

results:

?f(10)
*
**
***
****
*****
******
*******
********
*********
**********
?f(2)
*
**

?f(5)
*
**
***
****
*****

krish KM

Posted 9 years ago

Reputation: 141

1

C++, 78 bytes

I don't know how there are 2 C++ answers that don't just do it with for loops. Very short and sweet this way:

void T(int n){for(int i=1;i<=n;i++){for(int j=0;j<i;j++)cout<<'*';cout<<'\n';}}

Full program

#include <iostream>

using namespace std;

void T(int n)
{
    for(int i = 1; i <= n; i++)
    {
        for(int j = 0; j < i; j++)
            cout << '*';
        cout << '\n';
    }
}

int main()
{
  T(5);
}

Edit: it is unclear to me whether to count the #include<iostream>, using namespace std, and/or std::whatever in calls. C/C++ answers all over this site seem to use both, and for the most part no one seems to care except for the occasional comment. If I need the std::, then +10. If I need the #include<iostream>, +18 (although GCC allows me to do without the basic includes, so maybe not that one)

Cody

Posted 9 years ago

Reputation: 447

1

Common Lisp (Lispworks), 71 bytes

(defun f(n)(dotimes(i n)(dotimes(j(1+ i))(format t"*"))(format t"~%")))

Usage:

CL-USER 170 > (f 5)
*
**
***
****
*****
NIL

Ungolfed:

(defun f (n)
  (dotimes (i n)
    (dotimes (j (1+ i))
      (format t "*"))
    (format t "~%")))

sadfaf

Posted 9 years ago

Reputation: 101

1

MoonScript, 31 bytes

(n)->for i=1,n
 print "*"\rep i

Sample call:

_ 5

manatwork

Posted 9 years ago

Reputation: 17 865

1

F#, 114 chars

[<EntryPoint>]
let main a =
 for i = 1 to System.Int32.Parse(a.[0]) do
  printfn "%s" <| String.replicate i "*"
 0

magumbasauce

Posted 9 years ago

Reputation: 21

Welcome to the site! I don't know anything about F#, but it looks like you might be able to take away some of the whitespace? – James – 9 years ago

Thanks! My first golf, both in my company and on the site. I did try and so far it looks like the other "type" of F# syntax is "verbose", which just gets longer. The indentation is the "light" syntax, which at minimum is a new line char and a space to indent. We do these in our slack channel but i didn't see any F# answers here, so i figured I would post! I can update with test cases but anyone can copy into a new F# console app and run pretty easily with VS 2015 Community and the F# tools, all of which are free. – magumbasauce – 9 years ago

1

Scala, 44 30 bytes (51 45 without asterisk, 41 for hourglass)

With asterisk in code (30 bytes):

(i:Int)=>(i to(1,-1))map("*"*) //create a range from i to 1 and map each number to that number of asterisks

Without asterisk (45 bytes):

(i:Int)=>(i to(1,-1))map(((41+1).toChar+"")*) //same as above, but without a literal asterisk

Without asterisk and easy ways of calculating 42 (57 bytes):

(i:Int)=>(i to(1,-1))map(((math sqrt("7G"##)).toChar+"")*)

## is the hashcode method, which returns 1764 for the string "7G", the square root of 1764 is 42, the ascii code for *

Hourglass:

(& :Int)=>((&to(1,-1))++(2 to&))map("*"*)

(& :Int)=>        //define an anonymus function with an int parameter called &
  (              
    (& to (1,-1))   //a range from & to 1, counting by -1, aka downwards
    ++              //concat
    (2 to&)         //a range from 2 to &
  )
  map(              //map each number to
    "*" *             //the string "*" repeated x times
  )

corvus_192

Posted 9 years ago

Reputation: 1 889

1@TheBitByte You're right, I didn't notice that I've used asterisks for multiplication / string repitition. I just thought that I could replace '*' with (7*6).toChar and that's it. – corvus_192 – 9 years ago

1The bounty spec is not really precise, it just states "other cheating methods". I have no idea what you consider cheating. – corvus_192 – 9 years ago

1@TheBitByte What do you consider acceptable then? sqrt(1764)? Building a sequence of 42 ones and summing them? Using a string used somewhere in the standard library and extract an asterisk from it? – corvus_192 – 9 years ago

1@TheBitByte It's your bounty, you can make the rules but you should precisely state what you allow and what you consider cheating. – corvus_192 – 9 years ago

1@TheBitByte I know that scala can't win against all those golfing languages – corvus_192 – 9 years ago

1

Braingasm, 27 bytes

Braingasm is a brainfuck variant with just a few more instructions and options. And this task would've been so much easier if I had bothered implementing that as many times as the value in the current cell thing yet..

;[->+[->+42.<]10.>[-<+>]<<]

Here's how it works:

;                           Read an integer from stdin and write it to cell#1
 [                        ] While the value of cell#1 is not zero,
  ->+                    <    substract one from cell#1 and add one to cell#2.
     [->+   <]                Each time, do the same between cell#2 and cell#3,
         42.                    but also print an asterix on the way.
              10.             Then print a newline.
                 >[-<+>]<     Move the value from cell#3 back to cell#2

daniero

Posted 9 years ago

Reputation: 17 193

1

Python 3, 196 Bytes

import contextlib as b,io;q=io.StringIO()
with b.redirect_stdout(q):import this
n=int(input());c=q.getvalue()[655];print(''.join([''.join([c for z in range(n)][:i+1])+'\n' for i in range(n)]))

This is probably counted as a cheat, but it uses the asterisk character in the import this string rather than explicitly writing an asterisk in the program code. It also doesn't use any asterisk multiplication operators. It temporarily rerouts stdout so as not to print the Zen of Python when run.

penalosa

Posted 9 years ago

Reputation: 505

1

05AB1E, 8 bytes

TžQè×.p»

Explanation coming soon

Oliver Ni

Posted 9 years ago

Reputation: 9 650

Isn't this answer (the no asterisk ver.) pretty much the same as yours?

– acrolith – 9 years ago

1

Element, 16 bytes

_'[1+'[\*`]\
`"]

Try it online!

Explanation:

This is a pretty simple nested-loop approach. Let N represent the newline in the source code.

_'[1+'[\*`]\N`"]
_'                take input and move it to the control stack
  [            ]  a FOR loop, each iteration = 1 line of output
  [1+          ]  increment the top of the stack, as a counter
  [  '         ]  move that value to the control stack
  [   [   ]    ]  another FOR loop, for the current line
  [   [\*`]    ]  output a literal asterisk
  [        \N` ]  output a literal newline
  [           "]  move the counter from control to main stack

PhiNotPi

Posted 9 years ago

Reputation: 26 739

1

C++, 63 bytes

void s(int n){if(n)s(n-1),cout<<setfill('*')<<setw(n+1)<<"\n";}

Usage:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    s(5);
}

Overrides the filling character (which is usually a space), and outputs an empty string (or actually a newline).

One weird thing about this code is the usage of if (...) - I cannot find a way to replace it by a conditional operator ... ? ... : ....

anatolyg

Posted 9 years ago

Reputation: 10 719

1

Swift 3, 86 bytes

for i in 1...Int(CommandLine.arguments[1])!{print(String(repeatElement("*",count:i)))}

Yuck. If I can drop the Int and String initializers I might be able to get this shorter than Java. Open to any optimizations.

Ungolfed:

import Foundation

guard CommandLine.argc > 1, let a = Int(CommandLine.arguments[1]) else {
    fatalError("Invalid or nonexistent argument")
}

for i in 1...a {
    print(String(repeatElement("*", count: i)))
}

Usage:

➜ ~ swift asterisk.swift 5
*
**
***
****
*****

JAL

Posted 9 years ago

Reputation: 304