ASCII Triangles

30

5

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!

Okx

Posted 2017-02-08T14:51:23.297

Reputation: 15 025

related – Rod – 2017-02-08T14:53:48.457

4Does it need to be a program or can it be a function? – fəˈnɛtɪk – 2017-02-08T15:04:15.223

8I 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) – user41805 – 2017-02-08T15:10:06.103

FYI: You can use <pre><br></pre> to have an empty code block (so you don't need an (empty) – Nathan Merrill – 2017-02-08T15:31:56.580

@TuukkaX as I said, output must be exactly as specified. – Okx – 2017-02-08T15:48:11.380

@LliwTelracs you can see in the top that I said a program. – Okx – 2017-02-08T15:49:37.137

4@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 – 2017-02-08T16:04:08.933

@LliwTelracs changed. Do you think I should allow functions? – Okx – 2017-02-08T16:17:59.710

@Okx I feel it is your choice but would prefer that there wasn't the additional restriction. – fəˈnɛtɪk – 2017-02-08T16:19:10.883

9I 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 – 2017-02-08T17:48:13.173

3The 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 – 2017-02-08T18:25:07.563

1I second @12Me12 - even if not intended, the edge case gives an... edge to the challenge. And changing challenges posted after answers are submitted is bad form. – Mindwin – 2017-02-08T19:04:29.917

@StewieGriffin a single dash wouldn't be a triangle, would it? :P – Okx – 2017-02-08T19:05:41.437

Is it acceptable to return the string? Or is printing mandatory? Quite a few answers here (including mine) are returning a string to save a few bytes. – adrianmp – 2017-02-09T07:43:52.507

1@adrianmp Since people have been doing both, I'd say you can return the string – Okx – 2017-02-09T10:43:38.800

1I assume that PETSCII substitutes for the ASCII characters are okay if it's for a C64/PET/VIC-20 etc...? – Shaun Bebbers – 2017-02-10T16:20:17.957

My original idea for suppressing output for x = 0 was originally x and x+1 but apparently that's not very efficient... – HyperNeutrino – 2017-03-05T02:46:14.637

Answers

3

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.  

Dennis

Posted 2017-02-08T14:51:23.297

Reputation: 196 637

11

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

Albert Renshaw

Posted 2017-02-08T14:51:23.297

Reputation: 2 955

1I managed to reach 68, was pretty proud of myself.. and then I scrolled :( -- Well done! – Quentin – 2017-02-08T23:58:11.147

1Very nice! Have a +1 – Steadybox – 2017-02-09T00:20:46.320

I have 2*n in there twice and it bothers me, can anyone think of a clever way to shorten it somehow? – Albert Renshaw – 2017-02-09T22:14:39.807

7

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

Jan

Posted 2017-02-08T14:51:23.297

Reputation: 610

6

05AB1E, 16 15 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

Emigna

Posted 2017-02-08T14:51:23.297

Reputation: 50 798

ð×.svy¦…|ÿ\}¹>'-×», guess my idea of .s wasn't as good as I thought. Nice use of ÿ, haven't seen that before. – Magic Octopus Urn – 2017-02-08T15:23:21.143

@carusocomputing: I considered .s as well as starting with <Ýð× but ran into trouble with the special case with those methods. – Emigna – 2017-02-08T15:26:35.950

FðN×…|ÿ\}Dg'-×» for 15 bytes – Adnan – 2017-02-08T15:33:23.317

@Adnan: Nice catch with Dg! Thanks :) – Emigna – 2017-02-08T15:37:49.487

.s also resulted in nested arrays and flattening which required more bytes. – Magic Octopus Urn – 2017-02-08T15:46:20.163

Trailing newlines not allowed, sorry! – Okx – 2017-02-08T15:50:16.883

@carusocomputing: Building the list with .p and then flattening would have saved a byte there. Still would have been two bytes or so longer than this. – Emigna – 2017-02-08T15:51:48.793

@Okx: That is now fixed. – Emigna – 2017-02-08T15:52:06.217

5

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

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!

user41805

Posted 2017-02-08T14:51:23.297

Reputation: 16 320

I should not have tried that hard for a byte Try it online!

– nmjcman101 – 2017-02-09T21:18:26.680

@nmjcman101 Ah, « of course. Clever! :) – user41805 – 2017-02-10T17:15:53.770

4

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

adrianmp

Posted 2017-02-08T14:51:23.297

Reputation: 1 592

3

CJam, 24 22 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

Business Cat

Posted 2017-02-08T14:51:23.297

Reputation: 8 927

3

Python 2, 69 bytes

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

Try it online!

Rod

Posted 2017-02-08T14:51:23.297

Reputation: 17 588

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 – 2017-02-09T06:24:20.543

2

SmileBASIC, 51 bytes

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

12Me21

Posted 2017-02-08T14:51:23.297

Reputation: 6 110

2

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.

AdmBorkBork

Posted 2017-02-08T14:51:23.297

Reputation: 41 581

The program prints a trailing newline but I asked output to be exactly as specified, sorry! – Okx – 2017-02-08T15:57:56.750

@Okx Changed at a cost of 16 bytes. – AdmBorkBork – 2017-02-08T16:02:05.980

2

C 101 93 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.

Abel Tom

Posted 2017-02-08T14:51:23.297

Reputation: 1 150

1You 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 – 2017-02-08T17:34:56.490

@Jens stimmt, Danke sehr :) Updated – Abel Tom – 2017-02-08T17:43:23.020

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 – 2017-02-08T18:14:09.390

To 69 bytes, actually: i;f(n){for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");} – Steadybox – 2017-02-08T18:28:23.863

@Steadybox 68: n--+1 can be shortened to ~n-- – Albert Renshaw – 2017-02-08T19:41:24.697

@Steadybox No need for two for loops, I can get it down to 58 bytes but at that point it's a totally different answer so I've posted it here: http://codegolf.stackexchange.com/a/109541/16513

– Albert Renshaw – 2017-02-08T20:00:38.880

@Steadybox Thanks for pointing out and saving 18 bytes – Abel Tom – 2017-02-09T18:46:02.807

2

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.

djeis

Posted 2017-02-08T14:51:23.297

Reputation: 281

2

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!

mbomb007

Posted 2017-02-08T14:51:23.297

Reputation: 21 944

2

Charcoal, 15 bytes

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

Try it online!

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

Mike Bufardeci

Posted 2017-02-08T14:51:23.297

Reputation: 1 680

Very late comment, but the closing » can be omitted. – DLosc – 2017-11-09T07:24:12.090

2

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

Oliver

Posted 2017-02-08T14:51:23.297

Reputation: 7 160

1Nice 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 – 2017-03-04T17:07:49.323

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 – 2017-03-04T18:44:32.137

2

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!

Jonah

Posted 2017-02-08T14:51:23.297

Reputation: 8 729

25 bytes with *,&'-' '|',.'\'{."0~_1-i. – miles – 2017-07-21T09:52:21.320

22 bytes with *,&'-' '|',.' \'{~=@i. – bob – 2017-07-23T09:09:44.997

@bob That was very clever to use identity matrix – miles – 2017-07-24T07:25:52.887

@bob thanks for the suggestion. i've updated the post – Jonah – 2017-11-09T03:14:32.217

1

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.

steenbergh

Posted 2017-02-08T14:51:23.297

Reputation: 7 772

1

Pyke, 18 17 bytes

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

Try it here!

Blue

Posted 2017-02-08T14:51:23.297

Reputation: 26 661

1

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

Luis Mendo

Posted 2017-02-08T14:51:23.297

Reputation: 87 464

1

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

Yytsi

Posted 2017-02-08T14:51:23.297

Reputation: 3 582

I apologise for my previous comment, functions are now allowed. – Okx – 2017-02-08T16:24:20.867

@Okx No problem. This stands as a full program. I don't think I'll look into the fashion of a function solution :) – Yytsi – 2017-02-08T16:25:19.667

1

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

Mike Bufardeci

Posted 2017-02-08T14:51:23.297

Reputation: 1 680

@Ven Thanks! You can cut off the last | for an additional byte. – Mike Bufardeci – 2017-02-22T20:59:48.440

1

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 = "")

Frédéric

Posted 2017-02-08T14:51:23.297

Reputation: 2 059

1Might want to fix the spelling of ungolfed – fəˈnɛtɪk – 2017-02-08T17:21:36.037

1

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.

xnor

Posted 2017-02-08T14:51:23.297

Reputation: 115 687

Apparently, functions do not have to print. – Yytsi – 2017-02-09T12:02:59.977

1

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.

Neil

Posted 2017-02-08T14:51:23.297

Reputation: 95 035

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 – 2017-02-08T21:12:12.120

1

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
|\
| \
|  \
|   \
-----

Laikoni

Posted 2017-02-08T14:51:23.297

Reputation: 23 676

1

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!

PidgeyUsedGust

Posted 2017-02-08T14:51:23.297

Reputation: 631

1

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+' ')

Dennis

Posted 2017-02-08T14:51:23.297

Reputation: 196 637

1

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.

Andy Lester

Posted 2017-02-08T14:51:23.297

Reputation: 111

1probably could save some by reading the input off of stdin?$n=<>? – Ven – 2017-02-22T19:17:40.567

1

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

Patrick Happel

Posted 2017-02-08T14:51:23.297

Reputation: 141

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. – Post Rock Garf Hunter – 2019-12-14T01:13:55.240

1

Python 3, 72 bytes

x=int(input())
for i in range(x):
    print('|'+' '*i+'\\')
print('-'*x)

First submission. Very basic and entry level.

Try it online!

Dion

Posted 2017-02-08T14:51:23.297

Reputation: 35

Welcome to Code Golf! You can remove three of your spaces to save 3 bytes. – Stephen – 2020-02-12T17:54:17.093

@Stephen, thanks! One question since im new, how do you cross out the previous score in the title? – Dion – 2020-02-14T05:51:59.973

You can use a <s> tag, so like <s>72</s>. – Stephen – 2020-02-14T05:58:09.640

You can actually remove all the spaces so that the for loop is on one line. Additionally, the last line of dashes should be one longer – Jo King – 2020-02-19T22:14:44.833

0

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

fəˈnɛtɪk

Posted 2017-02-08T14:51:23.297

Reputation: 4 166

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

Try it online!

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.

ElPedro

Posted 2017-02-08T14:51:23.297

Reputation: 5 301

You can do -~c*(c>0) on the last line to save 3 bytes :) – Yytsi – 2017-02-09T17:58:49.010

Or better yet: c and-~c. – Yytsi – 2017-02-10T17:42:58.167

0

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='|'+('&nbsp;'.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.

Ismael Miguel

Posted 2017-02-08T14:51:23.297

Reputation: 6 797

@LliwTelracs Should work now. If it is required to show the alert when it is 0, I can do it without increasing the size again. – Ismael Miguel – 2017-02-08T19:07:33.510

0

Befunge-98, 68 bytes

&:!#@_000pv<
:kg00 ',|'<|`g00:p00+1g00,a,\'$,kg00
00:k+1g00-'<@,k+1g

Uriel

Posted 2017-02-08T14:51:23.297

Reputation: 11 708

This looks like a very nice first answer, but when I try it online, I get the wrong results. Any idea what's wrong there?

– James – 2017-02-08T20:22:00.230

@DJMcMayhem I checked it, the TIO gives k instruction one more execution (executes pop()+1 times). Bug in their implementation. – Uriel – 2017-02-08T20:40:43.093

@UrielEli which interpreter are you using? According to a github issue there is one weird (cfunge) that does this,like you, but all the others, including TIO work as intended (see here https://github.com/catseye/FBBI/issues/1#issuecomment-272643932)

– Andrew Savinykh – 2017-02-08T21:10:57.060

0

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

Carcigenicate

Posted 2017-02-08T14:51:23.297

Reputation: 3 295

0

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.

Neil

Posted 2017-02-08T14:51:23.297

Reputation: 95 035

0

JavaScript, 66 bytes

f=(x,i=0)=>i<x?`|${" ".repeat(i)}\\\n`+f(x,i+1):"-".repeat(x&&i+1)

Huntro

Posted 2017-02-08T14:51:23.297

Reputation: 459

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.

Greg Martin

Posted 2017-02-08T14:51:23.297

Reputation: 13 940

0

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 = |\;| \;---

Esolanging Fruit

Posted 2017-02-08T14:51:23.297

Reputation: 13 542

0

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
|\
| \
|  \
|   \
-----

Chaos Manor

Posted 2017-02-08T14:51:23.297

Reputation: 521

0

Ruby, 48 bytes

->n{puts ?-*(n.times{|x|puts ?|+' '*x+?\\}+(n<=>0))}

G B

Posted 2017-02-08T14:51:23.297

Reputation: 11 099

0

Jelly, 19 bytes

Ḷ×⁶j@€⁾|\;‘×”-$$YxṠ

Try it online!

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.

Erik the Outgolfer

Posted 2017-02-08T14:51:23.297

Reputation: 38 134

0

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
|\
| \
|  \
|   \
|    \
------

Mitchell Spector

Posted 2017-02-08T14:51:23.297

Reputation: 3 392

0

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

Try it online!

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.

R. Kap

Posted 2017-02-08T14:51:23.297

Reputation: 4 730

0

Python 3, 75 bytes

def x(n):
 if n:
  for i in range(n):print('|'+' '*i+'\\')
  print('-'*-~n)

Try it online!

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

python-b5

Posted 2017-02-08T14:51:23.297

Reputation: 89

0

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.

Titus

Posted 2017-02-08T14:51:23.297

Reputation: 13 814

0

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+"-")

Leena

Posted 2017-02-08T14:51:23.297

Reputation: 131

Can you do var a=5,b=""; in Swift? – user41805 – 2017-02-14T12:17:37.797

Yes its possible – Leena – 2017-02-14T12:18:34.183

Also can't you do print(b+"-") instead of b+="-";print(b)? – user41805 – 2017-02-14T12:20:20.727

I guess now its perfect – Leena – 2017-02-14T12:27:23.433

Also var a=5,b="",d;for c in 0..<a{d="|" instead of the beginning of the loop if it works – user41805 – 2017-02-14T12:29:08.427

No that will increase 1 byte as the code will become var a=5,b="",d="";for c in 0..<a{d="|";for _ in 0..<c{d+=" "};print(d+"\");b+="-"};print(b+"-") – Leena – 2017-02-14T12:31:25.710

In Swift either you need to initialize a variable with any value or with the type. So it's better to initialize with the value – Leena – 2017-02-14T12:37:14.130

Ah sorry, I don't know Swift – user41805 – 2017-02-14T12:38:28.480

And by the way, welcome to PPCG! – user41805 – 2017-02-14T12:39:19.723

0

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
|\
| \
|  \
----

Marauder

Posted 2017-02-08T14:51:23.297

Reputation: 1

0

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)

remoel

Posted 2017-02-08T14:51:23.297

Reputation: 511

You can drop this down to 65 bytes For i=0To[A1-1]:?"|"String(i,32)"\":Next:If i Then?String(i+1,45) – Taylor Scott – 2017-12-18T18:22:03.237

0

Python 3, 61 bytes

n=5
q="".join(map(lambda x:"|%s\\\n"%(x*" "),range(n)))+"-"*n

Try it online!

Cammy_the_block

Posted 2017-02-08T14:51:23.297

Reputation: 101

0

Perl 5, 50 +2 (-ap) = 52 bytes

$_&&='|\\';say,s/\\/ $&/ while$F[0]--;s/./-/g;chop

Try it online!

Xcali

Posted 2017-02-08T14:51:23.297

Reputation: 7 671

0

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
}

Try it online!

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

DLosc

Posted 2017-02-08T14:51:23.297

Reputation: 21 213

0

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:

Try it here.

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

Kevin Cruijssen

Posted 2017-02-08T14:51:23.297

Reputation: 67 575

0

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

Try it online!

Giuseppe

Posted 2017-02-08T14:51:23.297

Reputation: 21 077

0

Japt -R, 14 bytes

°Æ'\i|úXÄÃpUç-

Try it

°Æ'\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

Shaggy

Posted 2017-02-08T14:51:23.297

Reputation: 24 623

0

Commodore BASIC (C64/128, TheC64 & Mini, VIC-20, PET, C16/+4) - byte count later; non-competing as this is PETSCII and not ASCII

0inputn:ifnthenfori=1ton:print"{shift+B}{left}"spc(i)"{shift+M}":next:fori=0ton: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.

Commodore C64 Triangle challenge

Shaun Bebbers

Posted 2017-02-08T14:51:23.297

Reputation: 1 814