| Bytes | Lang | Time | Link |
|---|---|---|---|
| 017 | Vyxal 3 | 250523T123557Z | Themooni |
| nan | Perl 5 | 171109T054742Z | Xcali |
| 052 | AWK | 250522T175204Z | xrs |
| 086 | ><> | 221104T191248Z | mousetai |
| 012 | Vyxal Ṁosr | 221013T010117Z | naffetS |
| 033 | APL Dyalog Unicode | 200902T040855Z | Razetime |
| 060 | Zsh | 201110T224959Z | roblogic |
| 021 | Pip n | 200902T050157Z | DLosc |
| 112 | C | 200410T081212Z | Muskovet |
| 015 | 05AB1E | 200410T071828Z | Command |
| 071 | Python 3 | 200212T161930Z | Dion |
| 161 | Haxe 4 | 200409T135108Z | Mark Kno |
| nan | Commodore BASIC C64/128 | 200212T140326Z | Shaun Be |
| 065 | JavaScript Babel Node | 200330T140405Z | Cristi |
| 039 | Underload | 170209T095452Z | Esolangi |
| 256 | brainf**k | 191214T002130Z | Patrick |
| 014 | Japt R | 191213T152857Z | Shaggy |
| 098 | SNOBOL4 CSNOBOL4 | 171219T212905Z | Giuseppe |
| 065 | VBA Excel | 171109T045432Z | remoel |
| 109 | Java 8 | 171109T085427Z | Kevin Cr |
| 179 | Acc!! | 171109T074517Z | DLosc |
| 061 | Python 3 | 171109T054355Z | cubecube |
| 020 | J | 170721T024400Z | Jonah |
| 089 | 8th | 170209T100844Z | Chaos Ma |
| 058 | C | 170208T200024Z | Albert R |
| 020 | Japt | 170303T154709Z | Oliver |
| 015 | Charcoal | 170302T212411Z | Mike Buf |
| 018 | Pyth | 170208T170758Z | Mike Buf |
| 075 | Python 3 | 170212T125321Z | python-b |
| 068 | bash + printf | 170214T173101Z | Marauder |
| 096 | Swift 3 | 170214T120349Z | Leena |
| 075 | PHP | 170214T082153Z | Titus |
| 065 | Haskell | 170208T222104Z | Laikoni |
| 016 | V | 170208T151822Z | user4180 |
| 098 | dc | 170210T033307Z | R. Kap |
| 071 | bash + Unix utilities | 170210T033244Z | Mitchell |
| 074 | Javascript ES6 | 170208T162956Z | Jan |
| 063 | Perl | 170209T213431Z | Andy Les |
| 060 | Python 3 | 170209T184515Z | Dennis |
| 075 | C | 170208T161955Z | Abel Tom |
| 014 | Jelly | 170209T173032Z | Dennis |
| 067 | Python 2 | 170209T173443Z | PidgeyUs |
| 8986 | Common Lisp | 170208T210722Z | djeis |
| 039 | Retina | 170209T150418Z | mbomb007 |
| 019 | Jelly | 170209T125411Z | Erik the |
| 048 | Ruby | 170209T113121Z | G B |
| 057 | Mathematica | 170209T091033Z | Greg Mar |
| 066 | JavaScript | 170209T080902Z | Huntro |
| 068 | Befunge98 | 170208T201525Z | Uriel |
| 071 | JavaScript ES6 | 170208T210419Z | Neil |
| 110 | Batch | 170208T205528Z | Neil |
| 104 | Clojure | 170208T204941Z | Carcigen |
| 062 | Python 2 | 170208T204736Z | xnor |
| 084 | Javascript ES6 | 170208T185315Z | Ismael M |
| 082 | Python 2 | 170208T184315Z | ElPedro |
| 101 | R | 170208T171205Z | Rudier |
| 041 | QBIC | 170208T145849Z | steenber |
| 079 | Javascript 101Full Program | 170208T153656Z | fəˈnɛtɪk |
| 019 | MATL | 170208T161317Z | Luis Men |
| 073 | Python2 | 170208T162328Z | Yytsi |
| 067 | PowerShell | 170208T150822Z | AdmBorkB |
| 016 | 05AB1E | 170208T151403Z | Emigna |
| 021 | CJam | 170208T151211Z | Business |
| 069 | Python 2 | 170208T151519Z | Rod |
| 093 | C# | 170208T151411Z | adrianmp |
| 051 | SmileBASIC | 170208T145732Z | 12Me21 |
| 017 | Pyke | 170208T150235Z | Blue |
Vyxal 3, 17 bytes
ʀƛ␣×Ꮬ|\$j}?›'-×&”
ʀƛ␣×Ꮬ|\$j}?›'-×&”
ʀƛ } # map over (0..input(
Ꮬ|\ # "|\"
$j # join by
␣× # " " times n
& # append
'-× # "-" times
?› # input +1
” # join by newlines
💎
Created with the help of Luminespire.
<script type="vyxal3">
ʀƛ␣×Ꮬ|\$j}?›'-×&␣p”
##note: ␣p is support code for pretty-printing in the snippet
</script>
<script>
args=[["3"],["6"]]
</script>
<script src="https://themoonisacheese.github.io/snippeterpreter/snippet.js" type="module"/>
><>, 86 bytes
:?!;01.
!0:@>"|"o>:?va"\"oo~:&$1+:&(?!v
"-"v>-^ ;8>1-:?!;53!.| >
o"-"o<^1o*4<^
Good luck figuring this out
Vyxal Ṁosr, 12 bytes
⟑I‛|\j…;tƛ\-
Flags FTW
⟑I‛|\j…;tƛ\-
⟑ # Over each in [0, n) (not [1, n] thanks to Ṁ flag)
I # Push n spaces
‛|\j # Join ['|', '\'] by that (r flag makes the arguments reversed)
… # Print it with a trailing newline (without popping)
; # Close loop
t # Get the last element
ƛ\- # Replace each with a hyphen
# o flag - force implicit output
# s flag - join this list of hyphens to a single string
APL (Dyalog Unicode), 41 33 bytes
{×⍵:↑({'\',⍨⍵↑'|'}¨⍳⍵),⊂'-'⍴⍨⍵+1}
-7 bytes from Adám.
-1 byte using signum function.
Explanation
{×⍵:↑({'\',⍨⍵↑'|'}¨⍳⍵),⊂'-'⍴⍨⍵+1} ⍝ ⍵=n
×⍵: ⍝ If sign(n)
'-'⍴⍨⍵+1 ⍝ Repeat '-' n+1 times
⊂ ⍝ Enclose it to a single string
, ⍝ Join with
}¨⍳⍵ ⍝ for each x in range 1..n
⍵↑'|' ⍝ Inner fn: take x characters from '|' appending spaces
'\',⍨ ⍝ Reverse join with '\'
Zsh, 60 bytes
for ((;i<$1;))printf "|%$[i++]s\\\\\n"&&a=$a-
(($1))&&<<<$a-
Try it Online. Credit to the bash solution.
Pip -n, 21 bytes
IaO['|.sX,a.'\'-Xa+1]
Explanation
IaO['|.sX,a.'\'-Xa+1]
s is space; a is 1st command-line arg (implicit)
Ia If a is nonzero:
O Output this expression without a trailing newline:
[ ] A list containing these two items:
sX,a A list of increasing runs of spaces
'|. with a pipe character concatenated to the front of each run
.'\ and a slash concatenated to the back
'-Xa+1 A string of a+1 hyphens
For example: with an input of 3, the list will be [["|\"; "| \"; "| \"]; "----"]. The -n flag separates all items of a list with newlines when it is printed, so we get
|\
| \
| \
----
The if statement means the program does nothing if the input a is 0, as required.
C, 115 112 bytes
i,n,w;f(){if(n){for(i=n;i--;){w=n-i;printf("|");for(;0<--w;)printf(" ");puts("\\");}for(i=n;~i--;)printf("-");}}
x86-32 machine code, 87 bytes
bd00 8089 ecbb 0400 83fb 0074 fe89 d989
d829 c850 b40e b07c cd10 5851 89c1 4183
f901 7502 7408 50b4 0eb0 20cd 1058 90e2
ee50 b40e b05c cd10 5850 b40e b00a cd10
b00d cd10 5859 e2c7 89d9 4150 b40e b02d
cd10 58e2 f6eb fe
To boot, pad it to 510 bytes with zeros and add 55aa at the end!
This means "add times 510 - ($-$$) db 0 and db 0xaa55 to the ungolfed assembly code".
Ungolfed (compilable, compile using nasm -fbin -o triangles triangles.asm):
[org 0x7c00]
[bits 16]
mov bp, 8000h ; set up stack
mov sp, bp
mov bx, 4 ; N
; cx = i, bx = n, ax = w
cmp bx, 0 ; if n == 0, don't print anything
je $
mov cx, bx ; i = n
l1: ; first for
mov ax, bx
sub ax, cx ; w = n - i
push ax
mov ah, 0eh
mov al, '|'
int 10h ; print |
pop ax
push cx
mov cx, ax
inc cx
l2: ; second for (prints whitespaces)
cmp cx, 1 ; if (i != 1) print " "; - there was a bug with first \ printing far right from the triangle
jne l2_1
je l2_2
l2_1:
push ax
mov ah, 0eh
mov al, ' '
int 10h
pop ax
l2_2:
nop
loop l2 ; while i < 0 l2(); i--;
push ax
mov ah, 0eh
mov al, '\'
int 10h ; print backslash
pop ax
push ax
mov ah, 0eh
mov al, 0ah
int 10h
mov al, 0dh
int 10h ; print newline
pop ax
pop cx
loop l1 ; while i < 0 l1(); i--;
mov cx, bx ; i = n
inc cx ; i++
l3: ; third for (prints dashes)
push ax
mov ah, 0eh
mov al, '-'
int 10h
pop ax
loop l3 ; while i < 0 l3(); i--;
jmp $ ; hang forever
```
Python 3, 72 71 bytes
x=int(input())
for i in range(x):print('|'+' '*i+'\\')
print('-'*(x+1))
Python 2, 62 bytes
x=input()
for i in range(x):print'|'+' '*i+'\\'
print'-'*(x+1)
Haxe 4 (161 bytes)
class T{static function main()trace((x->x==0?"":[for(i in 0...x+1)i==x?[for(i in 0...x+2)""].join("-"):"|"+[for(i in -1...i)""].join(" ")+"\\"].join("\n"))(3));}
Try Online (slightly bigger there since playground requires class to be called "Test")
Test
Save as T.hx, compile and run interpreted mode haxe --run T
How it works
class T {
static function main()
trace(
(x ->
x == 0
? ""
: [for (i in 0...x + 1)
i == x
? [for (i in 0...x + 2) ""].join("-")
: "|" + [for (i in -1...i) ""].join(" ") + "\\"
].join("\n")
)(3)
);
}
- A class and entrypoint (static function called
main) are required in Haxe. (3)is the input- The snippet compiles to of all Haxe compiler targets (C++, JavaScript, PHP, Python, Lua, JVM, Java, etc)
Commodore BASIC (C64/128, TheC64 & Mini, VIC-20, PET, C16/+4) - 46 BASIC Bytes
0inputn:ifnthenfori=1ton:?"{shift+B}{left}"spc(i)"{shift+M}":next:fori=.ton:print"-";:next
There is a sanity check for zero, but any other positive integer will work.
Note, a C64 has 25 rows and 40 columns text (some PETs and the C128 in VDC mode has 80 columns, the VIC-20 is 22 columns by 23 rows) so the output will be skewed if you exceed the screen limit in either direction.
I've added a screenshot so that you may see the PETSCII characters that I can't make happen in this listing.
JavaScript (Babel Node), 65 bytes
f=(n,s=`\\
`,l)=>n?'|'+s+f(n-1,' '+s,l||'-'.repeat(n&&n+1)):l||''
Underload, 58 39 bytes
:()~(|)~(~!((-):S~^S)~:S( )*(\
)S)~^^!^
Assumes the input is a Church numeral on the stack.
Explanation
stack (assume input N = 2):
(:*)
: keep a copy of the input on the bottom
(:*)(:*)
()~ insert the finalization snippet
(:*)()(:*)
(|)~ insert the accumulator
(:*)()(|)(:*)
(...)~^^ run (...) N times:
~!(...)~ set finalization snippet
(:*)((-):S~^S)(|)
:S output copy of accumulator
(:*)((-):S~^S)(|) output = |
( )* append space to accumulator
(:*)((-):S~^S)(| ) output = |
(\;)S output backslash and newline
(:*)((-):S~^S)(| ) output = |\;
~!(...)~ set finalization snippet
(:*)((-):S~^S)(| )
:S output copy of accumulator
(:*)((-):S~^S)(| ) output = |\;|
( )* append space to accumulator
(:*)((-):S~^S)(| ) output = |\;|
(\;)S output backslash and newline
(:*)((-):S~^S)(| ) output = |\;| \;
! delete accumulator
(:*)((-):S~^S) output = |\;| \;
^ execute finalization snippet:
(:*) output = |\;| \;
(-) push hyphen
(:*)(-) output = |\;| \;
:S output hyphen
(:*)(-) output = |\;| \;-
~^ repeat N times
(--) output = |\;| \;-
S print
output = |\;| \;---
brainf**k, 256 bytes
[-]>[-]+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<>++++++++++[>+>+++>++++>+++++++++>++++++++++++<<<<<-]>>++>+++++>++>++++<<<<<<[>[-]+>>>>>.>[>+<<<<<.>>>>-]>[-<+>]<<<.>>+<<<<<.<<-]>>>>>>>[<<<.>>>-]<<<<<<[>>>.<<<-]
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 <
## output additional minus
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.
Japt -R, 14 bytes
°Æ'\i|úXÄÃpUç-
°Æ'\i|úXÄÃpUç- :Implicit input of integer U
° :Postfix increment U
Æ :Map each X in the range [0,U)
'\ : Literal "\"
i : Prepend
|ú : "|" right padded with spaces to length
XÄ : X+1
à :End map
p :Push
Uç- : "-" repeated U (now incremented) times
:Implicit output, joined with newlines
SNOBOL4 (CSNOBOL4), 98 bytes
N =INPUT
T OUTPUT =LT(X,N) '|' DUPL(' ',X) '\' :F(E)
X =X + 1 :(T)
E OUTPUT =DUPL('-',X + 1)
END
VBA Excel, 68 65 bytes
Using Immediate Window and [a1] as input
for x=0to[a1]-1:?"|"string(x,32)"\":next:if x then?string(x+1,45)
Java 8, 109 bytes
n->{String r="|\\\n";int i=0;for(;++i<n;r+=r.format("|%"+i+"s\\%n",""));for(;i-->=0;r+="-");return n<1?"":r;}
Can most likely be golfed some more.
Explanation:
n->{ // Method with integer parameter and String return-type
String r="|\\\n"; // Result-string, starting at "|\" + new-line
int i=0; // Index-integer, starting at 0
for(;++i<n; // Loop (1) from 1 to `n` (exclusive)
r+= // Append to the result-String:
r.format("| // A literal "|"
%"+i+"s // + `i` amount of spaces
\\ // + a literal "\"
%n","") // + a new-line
); // End of loop (1)
for(;i-->=0; // Loop (2) from `n` down to 0 (inclusive)
r+="-" // Append that many literal "-" to the result-String
); // End of loop (2)
return n<1? // If the input was 0:
"" // Return an empty String
: // Else:
r; // Return the result-String
} // End of method
Acc!!, 179 bytes
N
Count d while _%60-10 {
(_/60*10+_%60-48)*60+N
}
_/60
Count r while _-r {
Write 124
Count s while r-s {
Write 32
}
Write 92
Write 10
}
Count h while _+3*_/(3*_-1)-h {
Write 45
}
Explanation
Load a number into the accumulator, print that many rows of | ... \, and print that many (plus 1) hyphens. Unless the number is 0, in which case print 0 hyphens. No trailing newline in any case.
Most of the code is quite straightforward (handy loop variable mnemonics: digit, row, space, and hyphen). The two interesting parts are inputting a multi-digit number and handling the 0 case.
Inputting a number
N
Count d while _%60-10 {
(_/60*10+_%60-48)*60+N
}
_/60
We divide the accumulator into two sections: _%60 stores the ASCII code of the character we just read, and _/60 stores the number we're constructing. We loop until _%60 is 10--that is, when we encounter a newline. Inside the loop, _%60 is the ASCII code of the new least-significant digit. _%60-48 is the digit itself. _/60 is the previous value of the number, so we multiply that by 10 and add the new digit to get the new value of the number: _/60*10+_%60-48. Multiply that quantity by 60 and add the next input character N, and we're ready to loop. After the loop finishes, we set the accumulator to _/60, the stored number itself.
Handling the 0 case
Count h while _+3*_/(3*_-1)-h {
My original loop condition was _+1-h: loop (accumulator + 1) times. But if the accumulator is 0, we want to loop 0 times, not 1. So instead of adding 1, we add 3*_/(3*_-1). When _ is 0, this quantity is 0. When _ is greater than 0, this quantity is 1 (since 3*_ is less than twice 3*_-1).
J, 20 bytes
-13 bytes thanks to bob
*#' \|-'{~3,~2,.=@i.
original: 33 bytes
(#&'| \'@(1,1,~])"0 i.),('-'#~>:)
ungolfed
(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)
8th, 94 89 bytes
Code
: f 0; dup ( "|" . ( " " . ) swap times "\\" . cr ) 0 rot n:1- loop n:1+ "-" swap s:* . ;
Explanation
The word f requires an integer input
: f \ n --
0; \ Exit if input equals to 0
dup \ Duplicate input on the stack
( "|" . \ Print a piece of the vertical side
( " " . ) swap times \ Print space between sides
"\\" . cr ) \ Print a piece of the slanted side
0 rot n:1- loop \ Repeat the above operation for the size required
n:1+ "-" swap s:* . \ Print the bottom side
;
Usage
ok> 4 f
|\
| \
| \
| \
-----
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
Japt, 20 bytes
Saved 2 bytes thanks to @ETHproductions
o@'|+SpX +'\Ãp-pUÄ)·
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
Charcoal, 15 bytes
Nβ¿β«↓β→⁺¹β↖↖β»
Breakdown
Nβ¿β«↓β→⁺¹β↖↖β»
Nβ assign input to variable β
¿β« » 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
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
Python 3, 75 bytes
def x(n):
if n:
for i in range(n):print('|'+' '*i+'\\')
print('-'*-~n)
Here's my Python 3 answer, and it's pretty long. I wonder how I can shorten it...
Thanks to Eric The Outgolfer for helping in the comments...
bash + printf, 68 bytes
for((;i<$1;))
{
a=$a-
printf "|%$[i++]s\\\\\n"
}
[ $a ] && echo $a-
Use "bash program_name number" to run. Sample run:
bash-4.1$ bash triangle 0
bash-4.1$ bash triangle 1
|\
--
bash-4.1$ bash triangle 2
|\
| \
---
bash-4.1$ bash triangle 3
|\
| \
| \
----
Swift 3 96 bytes
var a=5,b="";for c in 0..<a{var d="|";for _ in 0..<c{d+=" "};print(d+"\\");b+="-"};print(b+"-")
PHP, 75 bytes
(70 bytes if I used extended ascii)
for($p=str_pad;+$i<$argv[1];)echo$p("|",++$i),"\\
";echo$p("",$i+!!$i,"-");
takes input from command line argument. Run with -nr.
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
|\
| \
| \
| \
-----
V, 18 17 16 bytes
1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is 0
é\é|ÀñÙá ñÒ-xÀ«D
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
dc, 98 bytes
256?dse1+d[q]st1=t^124*23562+dsaP2sk[[lkd256r^32*la+dsaPd1+skle>y]srle1<r]dsyx[45Ple1-dse0!>q]dsqx
Explanation
This takes due advantage of dc's P command, which utilizes conversion to base 256 on most systems. Therefore, for any input n, the program first raises 256 to the n + 1th power, multiplies the result by 124 (ASCII character |), and then adds 256*92+10=23562 to the product (where 92 is equivalent to the character \ and 10 is the decimal value of the new-line (\n)). This results in a decimal number that when converted to base 256 with P results in the output |\\n where \n is the literal new-line character. A duplicate of this decimal number is also stored on top of register a.
Then, a "macro-loop" is invoked, as long as n > 1, in which a counter is incremented until n, beginning from 2, and, as the 3rd through nth base 256 digits are unset, 256 is raised to each of those increments, a result which is then multiplied by 32 (the ASCII single space character). Then the value on top of register a is incremented by the resulting product, thus, on each iteration, setting each one of the unset base 256 digits in the between the | and the \ characters to a single space.
Finally, after all n-1 lines have been output, another "macro-loop" is invoked in which all the n+1 dashes are output through the feeding of 45 to P on each iteration.
Note: The [q]st1=t segment makes sure that nothing is output for the input 0 by checking if the incremented input is equal to one, and if it is, simply executes the macro [q] which exits the program.
bash + Unix utilities, 71 bytes
(($1))&&(echo '|\';(($1-1))&&$0 $[$1-1]|sed 's/|/| /;s/-/--/'||echo --)
Test program:
for n in 0 1 2 3 4 5; do echo $n; ./triangle $n; echo; done
Test output:
0
1
|\
--
2
|\
| \
---
3
|\
| \
| \
----
4
|\
| \
| \
| \
-----
5
|\
| \
| \
| \
| \
------
Javascript (ES6), 97 85 81 75 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))
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.
Python 3, 60 bytes
f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n
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+' ')
C 101 93 75 bytes
f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");}
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.
Jelly, 14 bytes
’⁶x⁾|\jṄµ€Ṫ”-ṁ
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.
Python 2, 67 bytes
Another function in Python 2, using rjust.
lambda n:('|'.join(map('\\\n'.rjust,range(n+2)))+'-'*-~n)[4:]*(n>0)
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.
Retina, 39 bytes
.*
$*
*\`(?<=(.*)).
|$.1$* \¶
1
-
-$
--
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!
Jelly, 19 bytes
Ḷ×⁶j@€⁾|\;‘×”-$$YxṠ
Explanation:
Ḷ×⁶j@€⁾|\;‘×”-$$YxṠ Link 0. Arguments: z.
Ḷ Range from 0 to z - 1. [arg-z]
⁶ Space (' ').
× Product of x and y. [multi-char-string-warning]
⁾|\ Two char string ("|\").
j Join x on y.
@ Reverse arguments.
€ Convert this link to a map on the left argument.
‘ Increment z. [arg-z]
”- Character ('-').
× Product of x and y. [multi-char-string-warning]
$ Merge last two links to a monadic link.
$ Merge last two links to a monadic link.
; Concatenate x and y.
Y Join z on newlines ('\n').
Ṡ Sign of z. [arg-z]
x Repeat x y times.
Ruby, 48 bytes
->n{puts ?-*(n.times{|x|puts ?|+' '*x+?\\}+(n<=>0))}
Mathematica, 57 bytes
Array[{"|"," "~Table~#,"\\
"}&,#,0]<>Table["-",#+Sign@#]&
Unnamed function taking a nonnegative integer as input and returning a string-with-newlines. It deals with the special case of input 0 by noting that the number of dashes is equal to the input plus the sign of the input.
JavaScript, 66 bytes
f=(x,i=0)=>i<x?`|${" ".repeat(i)}\\\n`+f(x,i+1):"-".repeat(x&&i+1)
Befunge-98, 68 bytes
&:!#@_000pv<
:kg00 ',|'<|`g00:p00+1g00,a,\'$,kg00
00:k+1g00-'<@,k+1g
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.
Batch, 110 bytes
@set s=
@for /l %%i in (1,1,%1)do @call:c
@if %1 gtr 0 echo -%s: =-%
@exit/b
:c
@echo ^|%s%\
@set s= %s%
Special-casing 0 is no hardship as %s: =-% would fail anyway.
Clojure, 104 bytes
(fn[h](let[r #(apply str(repeat % %2))](doseq[n(range h)](println(str\|(r n\ )\\)))(print(r(inc h)\-))))
At least I should have lots of room to golf from here!
Loops over the range from 0 to h-1, printing a \|, then h-many spaces, then a \\. Finally, at the end, it prints h+1 many dashes.
(defn triangle [hypot-n]
(let [r #(apply str (repeat % %2))] ; Create a shortcut string repeat function, since I need it twice.
(doseq [line-n (range hypot-n)] ; Loop over the range 0 to hypot...
(println (str \| (r line-n \ ) \\))) ; Printing a bar, then line-n many spaces, then a slash
(print (r (inc hypot-n) \-)))) ; Then print the trailing dashes
Python 2, 62 bytes
n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n
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.
Javascript (ES6), 84 bytes
Creates an anonymous function that presents the result on an alert box. No output is present if 0.
i=>{for(X=i,a='';i--;)a='|'+(' '.repeat(i))+'\\\n'+a;X&&alert(a+('-'.repeat(++X)))}
If printing is really required (137 bytes):
i=>for(X=i,d=document.body;i--;)d.innerHTML='|'+(' '.repeat(i))+'\\<br>'+d.innerHTML;X&&window.print(d.innerHTML+=('-'.repeat(++X)))
Changes the HTML code and prints the page into a paper sheet. The page stays white if 0.
Python 2, 82 bytes
def f(i,c=0):
if c<i:print'|'+' '*c+'\\';f(i,c+1)
print'-'*((c+1,c)[c<1]);exit()
Longer that the other Python answers but a recursive function just to be different.
It feels wasteful using two print statements but I can't find a shorter way round it. Also the exit() wastes 7 to stop it printing decreasing number of - under the triangle.
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 = "")
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.
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))}
Function with return string
x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+`\\
`;return s+'-'.repeat(x&&x+1)}
Repeating characters in Javascript is dumb and so is suppressing newlines on output
MATL, 19 bytes
?'\|- '2GXyYc!3Yc!)
? % 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
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:
|\
| \
| \
| \
| \
| \
-------
PowerShell, 51 67 bytes
param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}
(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.
05AB1E, 16 15 16 bytes
Saved a byte thanks to Adnan
FðN×…|ÿ\}Dg'-×»?
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
CJam, 24 22 21 bytes
Saved 1 byte thanks to Martin Ender
ri_{S*'|\'\N}%\_g+'-*
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
Python 2, 69 bytes
lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])
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));
}
}
SmileBASIC, 51 bytes
INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)
