# ASCII Triangles

Your task is to write a program or a function that prints an ASCII triangle. They look like this:

|\
| \
|  \
----


Your program will take a single numeric input n, with the constraints 0 <= n <= 1000. The above triangle had a value of n=3.

The ASCII triangle will have n backslashes (\) and vertical bars (|), n+1 lines and dashes (-), and each line will have an amount of spaces equal to the line number (0-based, ie first line is line 0) besides the ultimate line.

## Examples:

Input:

4


Output:

|\
| \
|  \
|   \
-----


Input:

0


Output:

In this test case, the output must be empty. No whitespace.

Input:

1


Output:

|\
--


Input & output must be exactly how I specified.

This is , so aim for the shortest code possible!

• Does it need to be a program or can it be a function? – fəˈnɛtɪk Feb 8 '17 at 15:04
• I think it would be better if case 0 can have any unexpected output since it is an edge case (especially since you requested that the number of dashes must be one more than the input number) – Kritixi Lithos Feb 8 '17 at 15:10
• @Okx There are frequently questions where the asker says program but really meant program or function. You might want to clarify that you are asking for a FULL program – fəˈnɛtɪk Feb 8 '17 at 16:04
• I would definitely go for both program and function. That's the default rule if nothing else is specified. I would also remove the 0-edge case since it's a direct violation of "n+1 lines and dashes (-)". – Stewie Griffin Feb 8 '17 at 17:48
• The challenge would be too simple without the size=0 exception. Part of the challenge is figuring out a way to account for this with the least amount of extra code. – 12Me21 Feb 8 '17 at 18:25

# Jelly, 14 bytes

’⁶x⁾|\jṄµ€Ṫ”-ṁ


Try it online!

### How it works.

’⁶x⁾|\jṄµ€Ṫ”-ṁ  Main link. Argument: n

µ       Combine the links to the left into a chain.
€      Map the chain over [1, ..., n]; for each k:
’                 Decrement; yield k-1.
⁶x               Repeat the space character k-1 times, yielding a string.
⁾\j            Join the character array ['|', '\'], separating by those spaces.
Ṅ           Print the result, followed by a linefeed.
Ṫ      Tail; extract the last line.
This will yield 0 if the array is empty.
⁾-ṁ   Mold the character '-' like that line (or 0), yielding a string
of an equal amount of hyphen-minus characters.


# C, 58 bytes

i;f(n){for(i=2*n;~i--;printf(i<n?"-":"|%*c\n",2*n-i,92));}


--

Thanks to @Steadybox who's comments on this answer helped me shave a few bytes in my above solution

• I managed to reach 68, was pretty proud of myself.. and then I scrolled :( -- Well done! – Quentin Feb 8 '17 at 23:58
• Very nice! Have a +1 – Steadybox Feb 9 '17 at 0:20
• I have 2*n in there twice and it bothers me, can anyone think of a clever way to shorten it somehow? – Albert Renshaw Feb 9 '17 at 22:14

## Javascript (ES6), 97858175 74 bytes

n=>(g=(n,s)=>n?g(--n,|${" ".repeat(n)}\\ +s):s)(n,"")+"-".repeat(n&&n+1)  Turns out I wasn't using nearly enough recursion f=n=>(g=(n,s)=>n?g(--n,|${" ".repeat(n)}\\
+s):s)(n,"")+"-".repeat(n&&n+1)

console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))

# 05AB1E, 1615 16 bytes

Saved a byte thanks to Adnan

FðN×…|ÿ\}Dg'-×»?


Try it online!

Explanation

F       }         # for N in range [0 ... input-1]
ðN×              # push <space> repeated N times
…|ÿ\          # to the middle of the string "|\"
Dg       # get length of last string pushed
'-×    # repeat "-" that many times
»   # join strings by newline
?  # print without newline

• ð×.svy¦…|ÿ\}¹>'-×», guess my idea of .s wasn't as good as I thought. Nice use of ÿ, haven't seen that before. – Magic Octopus Urn Feb 8 '17 at 15:23
• @carusocomputing: I considered .s as well as starting with <Ýð× but ran into trouble with the special case with those methods. – Emigna Feb 8 '17 at 15:26
• FðN×…|ÿ\}Dg'-×» for 15 bytes – Adnan Feb 8 '17 at 15:33
• @Adnan: Nice catch with Dg! Thanks :) – Emigna Feb 8 '17 at 15:37
• .s also resulted in nested arrays and flattening which required more bytes. – Magic Octopus Urn Feb 8 '17 at 15:46

# V, 1817 16 bytes

1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is 0

é\é|ÀñÙá ñÒ-xÀ«D


Try it online!

Hexdump:

00000000: e95c e97c c0f1 d9e1 20f1 d22d 78c0 ab44  .\.|.... ..-x..D


### Explanation (outdated)

We first have a loop to check if the argument is 0. If so, the code below executes (|\ is written). Otherwise, nothing is written and the buffer is empty.

Àñ     ñ            " Argument times do:
é\é|              " Write |\
h             " Exit loop by creating a breaking error


Now that we got the top of the triangle, we need to create its body.

Àñ   ñ              " Argument times do:
Ù                 " Duplicate line, the cursor comes down
à<SPACE>         " Append a space


Now we got one extra line at the bottom of the buffer. This has to be replaced with -s.

Ó-                  " Replace every character with a -
x                " Delete the extra '-'


This answer would be shorter if we could whatever we want for input 0

# V, 14 13 bytes

é\é|ÀñÙá ñÒ-x


Try it online!

• I should not have tried that hard for a byte Try it online! – nmjcman101 Feb 9 '17 at 21:18
• @nmjcman101 Ah, « of course. Clever! :) – Kritixi Lithos Feb 10 '17 at 17:15

# C#, 93 bytes

n=>{var s=n>0?new string('-',n+1):"";while(n-->0)s="|"+new string(' ',n)+"\\\n"+s;return s;};


Anonymous function which returns the ASCII triangle as a string.

Full program with ungolfed, commented function and test cases:

using System;

class ASCIITriangles
{
static void Main()
{
Func<int, string> f =
n =>
{
// creates the triangle's bottom, made of dashes
// or an empty string if n == 0
var s = n > 0 ? new string('-', n + 1) : "";

// a bottom to top process
while ( n-- > 0)
// that creates each precedent line
s = "|" + new string(' ', n) + "\\\n" + s;

// and returns the resulting ASCII art
return s;
};

// test cases:
Console.WriteLine(f(4));
Console.WriteLine(f(0));
Console.WriteLine(f(1));
}
}


# Python 2, 69 bytes

lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])


Try it online!

• If you're printing it, you can save a few bytes by changing to python3, removing "".join and replacing it with the * operator and the sep argument in the sleep function, so lambda x:print(*['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)],sep="\n") – sagiksp Feb 9 '17 at 6:24

# CJam, 2422 21 bytes

Saved 1 byte thanks to Martin Ender

ri_{S*'|\'\N}%\_g+'-*


Try it online!

Explanation

ri                     e# Take an integer from input
_                    e# Duplicate it
{                   e# Map the following to the range from 0 to input-1
S*                 e#   Put that many spaces
'|               e#   Put a pipe
\              e#   Swap the spaces and the pipe
'\            e#   Put a backslash
N           e#   Put a newline
}%         e# (end of map block)
\        e# Swap the top two stack elements (bring input to the top)
_g+     e# Add the input's signum to itself. Effectively this increments any
e#  non-zero number and leaves zero as zero.
'-*  e# Put that many dashes


# SmileBASIC, 51 bytes

INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)


# PowerShell, 51 67 bytes

param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}  Try it online! (Byte increase to account for no trailing newline) Takes input $n and verifies it is non-zero. Then loops to construct the triangle, and finishes with a line of -. Implicit Write-Output happens at program completion.

• The program prints a trailing newline but I asked output to be exactly as specified, sorry! – Okx Feb 8 '17 at 15:57
• @Okx Changed at a cost of 16 bytes. – AdmBorkBork Feb 8 '17 at 16:02

# Retina, 39 bytes

.*
$* *\(?<=(.*)). |$.1$* \¶ 1 - -$
--


Try it online

Convert decimal input to unary. Replace each 1 with |<N-1 spaces>\¶, print, and undo replace. Replace each 1 with a hyphen, and the last hyphen with 2 hyphens. Tadaa!

# Common Lisp, 89 86 bytes

Creates an anonymous function that takes the n input and prints the triangle to *standard-output* (stdout, by default).

## Golfed

(lambda(n)(when(< 0 n)(dotimes(i n)(format t"|~v@t\\~%"i))(format t"~v,,,'-<~>"(1+ n))))


## Ungolfed

(lambda (n)
(when (< 0 n)
(dotimes (i n)
(format t "|~v@t\\~%" i))
(format t "~v,,,'-<~>" (1+ n))))


I'm sure I could make this shorter somehow.

## C 10193 75 bytes

f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)prin‌​tf("-");}


Ungolfed version

void f(int n)
{
int i;

for(i=0;i++<n;)
printf("|%*c\n",i,92);

for(;n--+1;)
printf("-");

}


@Steadybox Thanks for pointing out, makes a lot of sense.

• You can shave off a few bytes by replacing character constants with their ASCII value and moving the first i++ in the loop body. And why is printf("%c",'_'); so verbose? – Jens Feb 8 '17 at 17:34
• @Jens stimmt, Danke sehr :) Updated – Abel Tom Feb 8 '17 at 17:43
• This can be cut down to 74 bytes: i;f(n){for(i=0;i++<n;)printf("%c%*c\n",124,i,92);for(;n--+1;)printf("-");} – Steadybox Feb 8 '17 at 18:14
• To 69 bytes, actually: i;f(n){for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");} – Steadybox Feb 8 '17 at 18:28
• @Steadybox 68: n--+1 can be shortened to ~n-- – Albert Renshaw Feb 8 '17 at 19:41

# Charcoal, 15 bytes

Ｎβ¿β«↓β→⁺¹β↖↖β»


Try it online!

## Breakdown

Ｎβ¿β«↓β→⁺¹β↖↖β»
¿β«         »  if β != 0:
↓β           draw vertical line β bars long
→⁺¹β       draw horizontal line β+1 dashes long
↖      move cursor up one line and left one character
↖β    draw diagonal line β slashes long

• Very late comment, but the closing » can be omitted. – DLosc Nov 9 '17 at 7:24

# Japt, 20 bytes

Saved 2 bytes thanks to @ETHproductions

o@'|+SpX +'\Ãp-pUÄ)·


Try it online!

### Explanation

o@'|+SpX +'\Ãp-pUÄ)·
o                       // Creates a range from 0 to input
@                      // Iterate through the array
'|+                   // "|" +
SpX +              // S (" ") repeated X (index) times +
'\Ã            // "\" }
p-pU       // "-" repeated U (input) +1 times
Ä)·    // Join with newlines

• Nice one! You can save a byte by pushing the last row before joining: o@'|+SpX +'\Ãp'-pUÄ)· and due to a bug (really an unintentional side effect of auto-functions), you can then remove the ' in '-. – ETHproductions Mar 4 '17 at 17:07
• Actually, it's like that with all lowercase letters, not just p. That's so you can do e.g. m*2 to double each element, or mp2 to square each – ETHproductions Mar 4 '17 at 18:44

# J, 20 bytes

-13 bytes thanks to bob

*#' \|-'{~3,~2,.=@i.


Try it online!

## original: 33 bytes

(#&'| \'@(1,1,~])"0 i.),('-'#~>:)


### ungolfed

(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)


Try it online!

• 25 bytes with *,&'-' '|',.'\'{."0~_1-i. – miles Jul 21 '17 at 9:52
• 22 bytes with *,&'-' '|',.' \'{~=@i. – bob Jul 23 '17 at 9:09
• @bob That was very clever to use identity matrix – miles Jul 24 '17 at 7:25
• @bob thanks for the suggestion. i've updated the post – Jonah Nov 9 '17 at 3:14

## Pyke, 18 17 bytes

I Fd*\|R\\s)Qh\-*


Try it here!

# Python2, 73 bytes

n=input()
w=0
exec'print"|"+" "*w+"\\\\"+("\\n"+"-"*-~n)*(w>n-2);w+=1;'*n


A full program. I also tried string interpolation for the last line, but it turned out be a couple bytes longer :/

exec'print"|%s\\\\%s"%(" "*w,("\\n"+"-"*-~n)*(w>n-2));w+=1;'*n


Another solution at 73 bytes:

n=j=input()
exec'print"|"+" "*(n-j)+"\\\\"+("\\n"+"-"*-~n)*(j<2);j-=1;'*n


# Test cases

0:

1:
|\
--

2:
|\
| \
---

3:
|\
| \
|  \
----

6:
|\
| \
|  \
|   \
|    \
|     \
-------

• I apologise for my previous comment, functions are now allowed. – Okx Feb 8 '17 at 16:24
• @Okx No problem. This stands as a full program. I don't think I'll look into the fashion of a function solution :) – Yytsi Feb 8 '17 at 16:25

# MATL, 19 bytes

?'\|- '2GXyYc!3Yc!)


Try it online!

?         % Implicit input. If non-zero
'\|- '  %   Push this string
2       %   Push 2
G       %   Push input
Xy      %   Identity matrix of that size
Yc      %   Prepend a column of 2's to that matrix
!       %   Transpose
3       %   Push 3
Yc      %   Postpend a column of 3's to the matrix
!       %   Transpose
)       %   Index into string
% Implicit end. Implicit display


## QBIC, 41 bytes

:~a>0|[a|?@|+space$(b-1)+@\][a+1|Z=Z+@-  Explanation :~a>0| Gets a, and checks if a > 0 If it isn't the program quits without printing anything [a| For b=1; b <= a; b++ ?@|+ Print "|" space$  and a number of spaces
(b-1)   euqal to our current 1-based line - 1
+@\    and a "\"
]       NEXT
[a+1|   FOR c=1; c <= a+1; c++
Z=Z+@-  Add a dash to Z$Z$ gets printed implicitly at the end of the program, if it holds anything
The last string literal, IF and second FOR loop are closed implicitly.


## R, 101 bytes

for(i in 1:(n=scan())){stopifnot(n>0);cat("|",rep(" ",i-1),"\\\n",sep="")};cat("-",rep("-",n),sep="")


This code complies with the n=0 test-case if you only consider STDOUT !
Indeed, the stopifnot(n>0) part stops the script execution, displays nothing to STDOUT but writes Error: n > 0 is not TRUE to SDTERR.

Ungolfed :

for(i in 1:(n=scan()))
{
stopifnot(n>0)
cat("|", rep(" ", i-1), "\\\n", sep = "")
}

cat("-", rep("-", n), sep = "")

• Might want to fix the spelling of ungolfed – fəˈnɛtɪk Feb 8 '17 at 17:21

# Python 2, 62 bytes

n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n


Try it online!

Prints line by line, each time adding another space before the backslash. If a function that doesn't print would be allowed, that would likely be shorter.

• Apparently, functions do not have to print. – Yytsi Feb 9 '17 at 12:02

## JavaScript (ES6), 71 bytes

f=
n=>console.log(' '.repeat(n).replace(/./g,'|$\\\n')+'-'.repeat(n+!!n)) <form onsubmit=f(+i.value);return!true><input id=i type=number><input type=submit value=Go!> Outputs to the console. Save 6 bytes if printing to the SpiderMonkey JavaScript shell is acceptable. Save 13 bytes if returning the output is acceptable. • That regex is ingenious. I first tried something along those lines. I din't know about the $ pattern, but don't know if I still would've thought of it. Nice. – Jan Feb 8 '17 at 21:12

# Python 2, 67 bytes

Another function in Python 2, using rjust.

lambda n:('|'.join(map('\\\n'.rjust,range(n+2)))+'-'*-~n)[4:]*(n>0)


Try it online!

# Python 3, 60 bytes

f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n


Try it online!

Two more solutions with the same byte count.

f=lambda n,k=0:n and'|'+' '*k+'\\\n'+f(n-1,k+1)or-~k*'-'[:k]
f=lambda n,s='|':-~n*'-'[:n]if s[n:]else s+'\\\n'+f(n,s+' ')


# Perl, 63 bytes

$n=shift;print'|',$"x--$_,"\\\n"for 1..$n;print'-'x++$n,$/if$n  Ungolfed: $ perl -MO=Deparse triangle.pl
$n = shift @ARGV; print '|',$" x --$_, "\\\n" foreach (1 ..$n);
print '-' x ++$n,$/ if $n;  $" is the list separator, which defaults to " ". $/ is the output record separator, which defaults to "\n". $_ is the implicit loop variable.

• probably could save some by reading the input off of stdin?$n=<>? – Ven Feb 22 '17 at 19:17 # Haskell, 82 65 bytes g 0="" g n=((take n$iterate(' ':)"\\\n")>>=('|':))++([0..n]>>"-")


Try it online! Usage:

Prelude> g 4
"|\\\n| \\\n|  \\\n|   \\\n-----"


Or more nicely:

Prelude> putStr \$ g 4
|\
| \
|  \
|   \
-----


# Pyth, 23 18 bytes

VQ++\|*dN\\)IQ*\-h


Test suite available online.
Thanks to Ven for golfing off 5 bytes.

## Explanation

VQ++\|*dN\\)IQ*\-h
Q           Q    Q  [Q is implicitly appended, initializes to eval(input)]
d             [d initializes to ' ' (space)]
VQ         )         For N in range(0, eval(input)):
*dN             Repeat space N times
+\|                Prepend |
+      \\           Append \
Implicitly print on new line
IQ       If (input): [0 is falsy, all other valid inputs are truthy]
hQ   Increment input by 1
*\-     Repeat - that many times
Implicitly print on new line

• @Ven Thanks! You can cut off the last | for an additional byte. – Mike Bufardeci Feb 22 '17 at 20:59

# brainf**k, 256 bytes

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


Try it online!

## How it works

# Read input and convert to number (https://esolangs.org/wiki/Brainfuck_algorithms#Input_a_decimal_number)
[-]>[-]+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<

# We need the characters {LF} (10); {space} (32); {minus} (45); \(92) | (120)

P1 > ++++++++++
[
p0  <
P1  >
P2  >  +
P3  >  +++
P4  >  ++++
P5  >  +++++++++
P6  >  ++++++++++++
P5  <
P4  <
P3  <
P2  <
P1  < -
]
P0 <           # Contains n
P1 >           # is zero
P2 >           # is {LF}
P3 > ++        # is {space}
P4 > +++++     # is {minus}
P5 > ++        # is \
P6 > ++++      # is |
p5 <
p4 <
p3 <
p2 <
p1 <
p0 <
[           # Loop through n
P1 >[-]+       # p1 will be 1 if input was not 0; used to output the additional {minus}
p2 >
p3 >
p4 >
p5 >
p6 > .
## output p7 spaces; copy p7 to p8
p7 >
[
p8 > +
p7 <
p6 <
p5 <
p4 <
p3 < .  # output {space}
p4 >
p5 >
p6 >
p7 > -
]
## copy p8 back to p7
p8 >
[
-
p7 < +
p8 >
]
p7 <
p6 <
p5 < . # output \
p6 >
p7 > + # increase number of spaces
p6 <
p5 <
p4 <
p3 <
p2 < . # output {LF}
p1 <
p0 < -
]
p1 >
p2 >
p3 >
p4 >
p5 >
p6 >
## output p7 minuses
p7 >
[
p6 <
p5 <
p4 < .
p5 >
p6 >
p7 > -
]
p6 <
p5 <
p4 <
p3 <
p2 <
p1 <
[
p2 >
p3 >
p4 > .
p3 <
p2 <
p1 < -
]


This is my first contribution and I'm not sure whether it is allowed to re-use code from others. My code above uses the code published in the Wiki to read the input characters and convert them into a number. Hope that's okay.

New contributor
Patrick Happel is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• Welcome to the site! It is ok to use code that is freely available here. However I will say that we do usually allow brainfuck to take input by character code. It does depend on the challenge a bit, because character codes are usually limited to 255, but with the right interpreter or compiler this bound is often optional. – Wheat Wizard 21 hours ago

## Javascript 101(Full Program), 94(Function Output), 79(Return) bytes

Full Program

Will not run in Chrome (as process doesn't exist apparently)
Will not run in TIO (as prompt apparently isn't allowed)

x=prompt();s='';for(i=0;i<x;i++)s+='|'+' '.repeat(i)+\\
;process.stdout.write(s+'-'.repeat(x&&x+1))


Function with EXACT print

x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+\\
;process.stdout.write(s+'-'.repeat(x&&x+1))}


Try it Online

Function with return string

x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+\\
;return s+'-'.repeat(x&&x+1)}
`

Try it Online

Repeating characters in Javascript is dumb and so is suppressing newlines on output