21
\$\begingroup\$

Given an integer n>0, write a program that will output an "isosceles" Triangle out of #'s of height n.

Examples:

n=3

  #  
 ### 
#####

n=1

#

n=5

    #    
   ###   
  #####  
 ####### 
#########

This would be invalid:

#
###
#####
#######
#########
\$\endgroup\$
  • 1
    \$\begingroup\$ Are leading and trailing newlines allowed? \$\endgroup\$ – S.S. Anne Feb 6 at 21:45
  • 15
    \$\begingroup\$ How is this not a duplicate? XD \$\endgroup\$ – RGS Feb 6 at 22:06
  • 1
    \$\begingroup\$ May we use another character besides #? \$\endgroup\$ – Shaggy Feb 7 at 0:38
  • 1
    \$\begingroup\$ Which isosceles triangle permitted? For the input 3 is the triangle shown the only allowed triangle? Could you be a little more specific with you challenge? \$\endgroup\$ – Ad Hoc Garf Hunter Feb 7 at 2:47
  • 2
    \$\begingroup\$ Related: Diamond creator + \$\endgroup\$ – Kevin Cruijssen Feb 7 at 9:06

35 Answers 35

9
\$\begingroup\$

Charcoal, 5 bytes

G↗↘N#

Try it online! Link is to verbose version of code. Explanation: The draws a filled polygon, where the ↗↘ specifies the sides to follow (the polygon is automatically closed) and the inputs the size and the # specifies the fill character. Using G↖↙N# also works of course.

Alternate solution, also 5 bytes:

G^N#⟲

Try it online! Link is to verbose version of code. Explanation: The ^ is a shortcut for two diagonal directions ↘↙ (sadly there is no shortcut for the above diagonals in the required order as < is ↘↗ and > is ↙↖) so the triangle has to be rotated into position using .

\$\endgroup\$
  • 2
    \$\begingroup\$ These are quite satisfying. \$\endgroup\$ – Jonah Feb 7 at 2:07
5
\$\begingroup\$

PowerShell, 36 bytes

"$args"..1|%{" "*--$_+"#"*++$i;$i++}

Try it online!

Loops from input $args down to 1, each iteration constructing a string consisting of the appropriate number of spaces plus a number of # marks that starts at 1 and increments by 2 every iteration. Those strings are left on the pipeline, and implicit output gives us newlines for free.

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

Python 2, 46 bytes

def f(n,i=1):1/n;print" "*~-n+"#"*i;f(n-1,i+2)

Try it online!

Basically the same solution as Jonathan Allan, but a function that prints and terminates with error, if that's allowed here. The 1/n is used to halt execution where n=0. Maybe there's a way to do that shorter by stuffing in a /n or %n somewhere.

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

05AB1E, 8 bytes

Multiple 8 bytes programs are possible:

Explanations:

·         # Double the (implicit) input-integer
          #  i.e. 3 → 6
 ÅÉ       # Pop and push a list of all positive odd values below this doubled value
          #  → [1,3,5]
   '#×   '# Repeat "#" that many times as string
          #  → ["#","###","#####"]
      .c  # Centralize this list (which implicitly joins by newlines)
          #  → "  #\n ###\n#####"

L         # Push a list in the range [1, (implicit) input-integer]
          #  i.e. 3 → [1,2,3]
 '#×     '# Repeat "#" that many times as list
          #  → ["#","##","###"]
    €û    # Palindromize each
          #  → ["#","###","#####"]
      .c  # Centralize this list (which implicitly joins by newlines)
          #  → "  #\n ###\n#####"

L         # Push a list in the range [1, (implicit) input-integer]
          #  i.e. 3 → [1,2,3]
 ·        # Double each value
          #  → [2,4,6]
  <       # Decrease each by 1
          #  → [1,3,5]
   '#×.c '# Same as the first answer above

'#×      '# Repeat "#" the (implicit) input-integer amount of times as string
          #  i.e. 3 → "###"
   η      # Take the prefixes of that string
          #  → ["#","##","###"]
    j     # Pad spaces to each to make the total length equal to the (implicit) input
          #  i.e. 3 → ["  #"," ##","###"]
     €û   # Palindromize each
          #  → ["  #  "," ### ","#####"]
       »  # Join by newlines
          #  → "  #  \n ### \n#####"

For each of these programs the resulting string is then output implicitly (with trailing newline).

\$\endgroup\$
  • \$\begingroup\$ There’s also Lx<'#×.c, for an almost ASCII-only 8-byter. \$\endgroup\$ – Grimmy Feb 7 at 9:39
  • \$\begingroup\$ @Grimmy True. I saw that approach as well here in this related challenge. I'm sure there are more equal-byte alternatives tbh. \$\endgroup\$ – Kevin Cruijssen Feb 7 at 9:47
  • 1
    \$\begingroup\$ @Grimmy Here another 8-bytes alternative (this time without centralize builtin): '#×ηj€û». :) \$\endgroup\$ – Kevin Cruijssen Feb 7 at 10:41
4
\$\begingroup\$

C (gcc), 104 \$\cdots\$ 72 71 bytes

Saved 5 11 bytes thanks to S.S.Anne!!!
Saved 6 bytes thanks to gastropner!!!
Saved a byte thanks to Stephen!!!

i;j;f(n){for(i=0;i++<n;)for(j=0;j<i*2;)printf(j++?"#":"\n%*s",n-i,"");}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ 84 bytes \$\endgroup\$ – S.S. Anne Feb 6 at 21:54
  • \$\begingroup\$ @S.S.Anne Nice one - thanks! :-) \$\endgroup\$ – Noodle9 Feb 6 at 21:58
  • \$\begingroup\$ It's 84, not 85. Saves 5 bytes. \$\endgroup\$ – S.S. Anne Feb 6 at 22:21
  • \$\begingroup\$ Anyway, 78 bytes with this comment. \$\endgroup\$ – S.S. Anne Feb 6 at 22:23
  • \$\begingroup\$ @S.S.Anne Sorry must have mixed up the 4 and 5 while editing on my phone. :-( \$\endgroup\$ – Noodle9 Feb 6 at 22:30
3
\$\begingroup\$

Ruby, 46 43 bytes

f=->g{g.times{|n|puts" "*(g-n)+?#*(2*n+1)}}

Try it online!

  • -3 thanks to IMP1
\$\endgroup\$
  • \$\begingroup\$ You could use g.times{} instead of (1..g).map{} to save 3 bytes (you'll need to change 2*n-1 to 2*n+1 as well). \$\endgroup\$ – IMP1 Feb 7 at 11:16
  • \$\begingroup\$ @IMP1 Nice tip, thanks. \$\endgroup\$ – 79037662 Feb 7 at 16:47
  • \$\begingroup\$ use p instead of puts \$\endgroup\$ – canhascodez Feb 7 at 19:39
  • 1
    \$\begingroup\$ @canhascodez That makes it print the quotation marks, which isn't valid as far as I know. \$\endgroup\$ – 79037662 Feb 8 at 0:16
  • \$\begingroup\$ @79037662 D: you're right \$\endgroup\$ – canhascodez Feb 8 at 18:47
3
\$\begingroup\$

J, 19 18 bytes

' #'(#~|.,.1++:)i.

Try it online!

-1 byte thanks to FrownyFrog

Let's do 3:

  • i. Produces:

    0 1 2
    
  • |.,.1++: - Reverse |. produces 2 1 0 and 1 + the double +: produces 1 3 5. Then we zip ,. those together:

    2 1
    1 3
    0 5
    
  • ' #'#~ copies each character in the 2-character string # (space and pound) according to the mask specified above, and pads the end of the first two rows with spaces, so every row is 5 characters:

      #  
     ### 
    #####
    
\$\endgroup\$
  • \$\begingroup\$ save one: ' #'(#~|.,.1++:)i. \$\endgroup\$ – FrownyFrog Feb 10 at 19:46
  • \$\begingroup\$ Nice catch. Thanks as always! \$\endgroup\$ – Jonah Feb 11 at 0:08
2
\$\begingroup\$

cQuents, 18 bytes

|
&@ (n-$)~@#(2$-1

Try it online!

Explanation

|
                   terms in sequence are separated by newline
&                  output first n terms in sequence
                   each term is:
 @                 " " *
   (n-$)                 n - index
        ~                          concat
         @#                               "#" *
           (2$-1                                2 * index - 1
\$\endgroup\$
2
\$\begingroup\$

APL+WIN, 23 bytes

Prompts for integer:

(-⌽⍳n)⌽⊃(1+2×⍳n←⎕)⍴¨'#'

Try it online! Courtesy of Dyalog Classic

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

MATL, 11 bytes

:&<~P2&ZvZc

Try it online!

How it works

Consider input 3 as an example.

:      % Implicit input. Range
       % STACK: [1 2 3]
&<     % Pairwise less-than comparison
       % STACK: [0 0 0;
                 1 0 0
                 1 1 0]
~      % Negate, elementwise
       % STACK: [1 1 1;
                 0 1 1;
                 0 0 1]
P      % Flip vertically
       % STACK: [0 0 1;
                 0 1 1;
                 1 1 1]
2&Zv   % Reflect horizontally, without repeating last column
       % STACK: [0 0 1 0 0;
                 0 1 1 1 0;
                 1 1 1 1 1]
Zc     % Replace nonzeros by '#' and zeros by ' '
       % STACK: ['  #  '
                 ' ### ';
                 '#####']
       % Implicit display
\$\endgroup\$
2
\$\begingroup\$

Python 2, 48 bytes

n=input();v=1
while n:n-=1;print' '*n+'#'*v;v+=2

Try it online!


A fun 49 with an extra space of padding is:

s=' '*input()+'#'
while'#'>s:print s;s=s[1:]+'##'

Try that

\$\endgroup\$
  • \$\begingroup\$ In case the extra leading spaces aren't allowed, you can move the n-=1 to the start of the loop to get rid of them. I haven't found anything shorter than your solution; I suspect it's optimal. \$\endgroup\$ – xnor Feb 7 at 1:21
  • \$\begingroup\$ Ah true, thanks. \$\endgroup\$ – Jonathan Allan Feb 7 at 1:22
2
\$\begingroup\$

k4, 29 bytes

{(-x+!x)$|:'x#x("##",)\"# "}


{                          } /lambda with implicit arg `x`
              x("##",)\"# "  /function composition - cumulatively join (,) "##" to "# " x times and return intermediate results ("# ";"### ";"##### ") etc
            x#               /take x items
         |:'                 /reverse each
 (-x+!x)                     /enumerate x and subtract x from each (x=3 -> -3+0 1 2)
        $                    /pad, left-pads when left arg is negative
\$\endgroup\$
2
\$\begingroup\$

Red, 78 76 bytes

func[n][s: copy"#"repeat i n[print pad/left s n + i - 1 append s"##"take s]]

Try it online!

Alternative using Red's parse:

Red, 77 bytes

func[n][s: to""pad/left"#"n loop n[parse s[(print s take s)to"#"insert"##"]]]

Try it online!

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

Rule 222, 1 byte (noncompeting)

#

Wolfram codes describe a family of celular automata. While most behave in very simple ways, some of them show very complex behaviour. Rule 110 is even Turing complete.

Rule 222 is one of the "simple" ones. After n generations, it produces a triangle of n levels, as specified in the challenge. A synonymous cellular automata in this case is Rule 254.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 58 bytes

def f(n,i=1):print((n-i)*' '+(2*i-1)*'#');n>i and f(n,i+1)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ @Stephen You should write an answer -- it's considered a different language. \$\endgroup\$ – S.S. Anne Feb 6 at 22:32
1
\$\begingroup\$

Jelly, 11 bytes

>þ`UŒBị⁾ #Y

Try it online!

A full program that takes an integer argument and prints a triangle. If a monadic link returning a list of Jelly strings is acceptable, the final byte can be saved for 10 bytes.

Explanation

>þ`         | Outer table using greater than and 1..n as both left and right argument
   U        | Reverse order of inner lists
    ŒB      | Bounce inner lists (i.e. repeat each one in reversed order without duplicating the final character)
      ị⁾ #  | Index into [" ", "#"]
          Y | Join with newlines
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 30 bytes

2|*J' j|*iSj'#j|*iT2enq\[Z[unQ

Try it online!

Not left aligned, but functionally an isosceles triangle. Takes input as N.

2|*    # N*2
J      # Duplicate this number
' j|*  # 2N spaces
iS     # [2N..1] spaces as list
j      # Swap back
'#j|*  # 2N hashes
iT     # [1..2N] hashes as list
2en    # Take each odd
q\[Z[  # Zip together, and concatenate
un     # Add new lines between each element
Q      # Pretty print
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 75 70 bytes

i,m;f(n){m=n*2;for(i=m*n;i--;)putchar(i%m?abs(i%m-n)<n-i/m?35:32:10);}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Python 2, 54 bytes

n,i=input(),1
exec"print(n-i)*' '+(2*i-1)*'#';i+=1;"*n

Try it online!

Based on Jitse's Python 3 solution.

\$\endgroup\$
1
\$\begingroup\$

Japt -R, 9 bytes

õî'# mê û

Try it

Or 7 bytes if we can choose which character to use.

õ_î¬êÃû

Try it

\$\endgroup\$
1
\$\begingroup\$

Haskell, 57 bytes

r=replicate
f x=unlines[r(x-n)' '++r(2*n-1)'#'|n<-[1..x]]

Try it online!

The unlines function is often helpful for ASCII art problems.

\$\endgroup\$
1
\$\begingroup\$

Japt -R, 9 bytes

ÇÑÄ ç'#
û

Try it

\$\endgroup\$
1
\$\begingroup\$

MathGolf, 18 17 bytes

╒_'#*mñ\x *^my ═n

Try it online.

Explanation:

╒                  # Push a list in the range [1, (implicit) input-integer]
                   #  3 → [1,2,3]
 _                 # Duplicate this list on the stack
  '#*             '# Repeat "#" the values amount of time as string
                   #  → ["#","##","###"]
     mñ            # Palindromize each
                   #  → ["#","###","#####"]
       \           # Swap to get the duplicated [1, input] list at the top again
        x          # Reverse this to [input, 1]
                   #  → [3,2,1]
          *        # Repeat a space the values amount of time as string
                   #  → ["   ","  "," "]
           ^       # Zip the two lists together
                   #  → [["#","   "],["###","  "],["#####"," "]]
            my     # Join each inner pair together
                   #  → ["#   ","###  ","##### "]
               ═   # Pad leading spaces to each string to make them all of equal length
                   #  → ["  #   "," ###  ","##### "]
                n  # And join this list by newlines
                   #  → "  #   \n ###  \n##### "
                   # (after which the entire stack is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

Canvas, 6 bytes

{#×]±│

Try it online.

Explanation:

{        # Map over the range [1, input]:
  #×      #  Repeat "#" the value amount of times
    ]±   # After the map: interpret the array as a 2D string, and reverse it
       │  # And palindromize it horizontally with 1 overlap
          # (after which it is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

Icon, 73 bytes

procedure f(n,i)
/i&i:=1
write(right(repl("#",i),n+i))
n>1&f(n-1,i+2)
end

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Stax, 9 bytes

é─C:UÅ≤┘.

My first Stax answer. :)

Try it online or try it online unpacked (10 bytes).

Explanation (of the unpacked version):

'#*        '# Repeat "#" the (implicit) input-integer amount of times as string
            #  i.e. 3 → "###"
   |[       # Get the prefixes of this string
            #  → ["#","##","###]
     |>     # Padding leading spaces up to a length equal to the longest string
            #  → ["  #"," ##","###"]
       m    # Map over each line:
        |p  #  Palindromize the line
            #   → ["  #  "," ### ","#####"]
       m    # And the map also prints each line with trailing newline afterwards
            #  → "  #  \n"
            #    " ### \n"
            #    "#####\n"
\$\endgroup\$
1
\$\begingroup\$

PHP, 65 64 62 bytes

for($j=$argn+$i=1;--$j;$i+=2)printf("%{$j}s%'#{$i}s\n",'','');

Try it online!

Muuuuch better version with string formatting. I knew there was something, PHP is a templating language after all.. It couldn't be that bad for this kind of job!!

EDIT: saved 1 byte and removed the extra leading space by moving $i++ to the printf

EDIT2: saved 2 bytes with new strategy by @GuillermoPhillips (thanks!)

ORIGINAL NAIVE ANSWER:

PHP, 104 bytes

for($t='#';$i++<$argn;$s.=' ',$t="#$t#"){$r[$i*2]="$t\n";$r[($argn-$i)*2+1]=$s;}ksort($r);echo join($r);

Try it online!

\$\endgroup\$
  • \$\begingroup\$ $i is always multiplied by 2, maybe something there? \$\endgroup\$ – Guillermo Phillips Feb 7 at 9:16
  • \$\begingroup\$ @GuillermoPhillips Thanks but I was already on a much better way with printf.. If you have something for this one I'd be glad \$\endgroup\$ – Kaddath Feb 7 at 9:27
  • \$\begingroup\$ One with 62 bytes: Try it online \$\endgroup\$ – Guillermo Phillips Feb 7 at 10:37
  • \$\begingroup\$ @GuillermoPhillips Nice one! the strategy is different enough to post it as another answer if you want.. Or else I'll credit you ;) \$\endgroup\$ – Kaddath Feb 7 at 10:49
  • \$\begingroup\$ Nah I don't want to steal the glory, it's based on yours anyway, never would have come up with it from scratch. \$\endgroup\$ – Guillermo Phillips Feb 7 at 11:07
1
\$\begingroup\$

Java 8, 151 128 bytes

p->{for(int c=1;p>0;c+=2)System.out.println(new String(new char[p--]).replace('\0',' ')+new String(new char[c]).replace('\0','#'));}

TIO

See also JDK 13 answer

\$\endgroup\$
  • \$\begingroup\$ Hi, welcome (back) to CGCC! Here is the TIO of your current answer. In addition, you can use a leading # to make your first line a title (so #Java 8, 151 bytes in this case). As for golfs: 1) since you're using Java 8, you can use a lambda, so void t(int p) can become p->. 2) int c=1;while(p>0){...;p--;c+=2;} can become for(int c=1;p>0;c+=2)...; and change the p-1 to --p. 3) In addition, using Java 11+, you can use "#".repeat(int) instead of new String(new char[int]).replace('\0','#'). In total: 76 bytes. \$\endgroup\$ – Kevin Cruijssen Feb 7 at 10:11
  • \$\begingroup\$ In case you haven't seen them yet, tips for golfing in Java and tips for golfing in <all languages> might both be interesting to read through. PS: Your current answer is 150 bytes, not 151? \$\endgroup\$ – Kevin Cruijssen Feb 7 at 10:12
1
\$\begingroup\$

Haskell, 52 bytes

f x=do n<-[1..x];'\n':([n..x]>>" ")++([2..2*n]>>"#")

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Haskell, 91 72 62 bytes

(1!)
_!0=""
i!n=r n ' '++r i '#'++'\n':(i+2)!(n-1)
r=replicate

-10 bytes thanks to @Laikoni.

You can try it online!

\$\endgroup\$
  • \$\begingroup\$ "\n"++ can be '\n':. Defining f with two arguments instead of one tuple as argument would save some more bytes, and defining f as infix operator would be even shorter. Finally, the g= is usually not counted by convention. All together 62 bytes: Try it online! \$\endgroup\$ – Laikoni Feb 7 at 18:18
  • \$\begingroup\$ @Laikoni all clever tricks! Thanks for the tips :) \$\endgroup\$ – RGS Feb 7 at 18:38
  • \$\begingroup\$ @Laikoni what is the -cpp flag for? \$\endgroup\$ – RGS Feb 7 at 18:39
  • 1
    \$\begingroup\$ @RGS Apparently it lets you put the g= outside the byte counted part. \$\endgroup\$ – 79037662 Feb 8 at 0:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.