# Give me Triangles [duplicate]

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:

#
###
#####
#######
#########
• Are leading and trailing newlines allowed? – S.S. Anne Feb 6 at 21:45
• How is this not a duplicate? XD – RGS Feb 6 at 22:06
• May we use another character besides #? – Shaggy Feb 7 at 0:38
• 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? – Ad Hoc Garf Hunter Feb 7 at 2:47
• Related: Diamond creator + – Kevin Cruijssen Feb 7 at 9:06

# Charcoal, 5 bytes

Ｇ↗↘Ｎ#

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 Ｇ↖↙Ｎ# also works of course.

Alternate solution, also 5 bytes:

Ｇ^Ｎ#⟲

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 .

• These are quite satisfying. – Jonah Feb 7 at 2:07

# 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. # 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. # 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). • There’s also Lx<'#×.c, for an almost ASCII-only 8-byter. – Grimmy Feb 7 at 9:39 • @Grimmy True. I saw that approach as well here in this related challenge. I'm sure there are more equal-byte alternatives tbh. – Kevin Cruijssen Feb 7 at 9:47 • @Grimmy Here another 8-bytes alternative (this time without centralize builtin): '#×ηj€û». :) – Kevin Cruijssen Feb 7 at 10:41 # 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! • 84 bytes – S.S. Anne Feb 6 at 21:54 • @S.S.Anne Nice one - thanks! :-) – Noodle9 Feb 6 at 21:58 • It's 84, not 85. Saves 5 bytes. – S.S. Anne Feb 6 at 22:21 • Anyway, 78 bytes with this comment. – S.S. Anne Feb 6 at 22:23 • @S.S.Anne Sorry must have mixed up the 4 and 5 while editing on my phone. :-( – Noodle9 Feb 6 at 22:30 # Ruby, 46 43 bytes f=->g{g.times{|n|puts" "*(g-n)+?#*(2*n+1)}} Try it online! • -3 thanks to IMP1 • 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). – IMP1 Feb 7 at 11:16 • @IMP1 Nice tip, thanks. – 79037662 Feb 7 at 16:47 • use p instead of puts – canhascodez Feb 7 at 19:39 • @canhascodez That makes it print the quotation marks, which isn't valid as far as I know. – 79037662 Feb 8 at 0:16 • @79037662 D: you're right – canhascodez Feb 8 at 18:47 # 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: # ### ##### • save one: ' #'(#~|.,.1++:)i. – FrownyFrog Feb 10 at 19:46 • Nice catch. Thanks as always! – Jonah Feb 11 at 0:08 # 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 # APL+WIN, 23 bytes Prompts for integer: (-⌽⍳n)⌽⊃(1+2×⍳n←⎕)⍴¨'#' Try it online! Courtesy of Dyalog Classic # 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 # 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 • 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. – xnor Feb 7 at 1:21 • Ah true, thanks. – Jonathan Allan Feb 7 at 1:22 # 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 # 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! # 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. # 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! • @Stephen You should write an answer -- it's considered a different language. – S.S. Anne Feb 6 at 22:32 # 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 # 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 # 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! # 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. # Japt-R, 9 bytes õî'# mê û Try it Or 7 bytes if we can choose which character to use. õ_î¬êÃû Try it # 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. # Japt-R, 9 bytes ÇÑÄ ç'# û Try it # 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) # 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) # 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! # Stax, 9 bytes é─C:UÅ≤┘. My first Stax answer. :) 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" # PHP, 6564 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!

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

# 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

• 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. – Kevin Cruijssen Feb 7 at 10:11
• 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? – Kevin Cruijssen Feb 7 at 10:12

# Haskell, 52 bytes

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

Try it online!

# Haskell, 9172 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!

• "\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! – Laikoni Feb 7 at 18:18
• @Laikoni all clever tricks! Thanks for the tips :) – RGS Feb 7 at 18:38
• @Laikoni what is the -cpp flag for? – RGS Feb 7 at 18:39
• @RGS Apparently it lets you put the g= outside the byte counted part. – 79037662 Feb 8 at 0:19