22
\$\begingroup\$

Given a strictly positive integer n (therefore 0 isn't a valid test case), produce an approximate triangle of height n.

A non-programmatic process of drawing the picture

Initially we start with the base of the triangle.

|

So, we want to draw a triangle of a height of 5. First we know that all the |'s align on a straight line, and there is a missing | on every even position.

|

|

|

Then, we insert the /'s onto these empty lines, where every / has 1 more preceding space than the next /. The lowest / starts at 1 space.

|
  /
|
 /
|

More reference outputs + Sample program

Here's what the program should output for inputs 1 to 9. A sample program is available if you still don't understand the specification.

For those that don't see that it's a triangle: Take a look at this. Scroll the picture really quickly. You will see the two sides of a triangle.

==== 1: ====
|
==== 2: ====
 /
|
==== 3: ====
|
 /
|
==== 4: ====
  /
|
 /
|
==== 5: ====
|
  /
|
 /
|
==== 6: ====
   /
|
  /
|
 /
|
==== 7: ====
|
   /
|
  /
|
 /
|
==== 8: ====
    /
|
   /
|
  /
|
 /
|
==== 9: ====
|
    /
|
   /
|
  /
|
 /
|

Specification

  • Leading/Trailing whitespace is allowed.
  • The string has to be joined with newlines, outputting a string list is not allowed.
\$\endgroup\$
  • \$\begingroup\$ Is a list of strings acceptable output from a function for this challenge? \$\endgroup\$ – Nick Kennedy Mar 5 at 14:26
  • 6
    \$\begingroup\$ It's an angle, not a triangle! \$\endgroup\$ – anatolyg Mar 5 at 15:08

28 Answers 28

3
\$\begingroup\$

05AB1E, 17 14 13 11 bytes

L'/ú€'|I£R»

-3 bytes thanks to @Grimmy.
-1 byte after getting inspiration from @MagicOctopusUrn.

Try it online or verify all test cases.

Explanation:

L            # Push a list in the range [1, (implicit) input]
             #  i.e. 5 → [1,2,3,4,5]
 '/ú        '# Pad "/" with that many leading spaces
             #  → [" /","  /","   /","    /","     /"]
    €'|     '# Put a "|" in front of each item
             #  → ["|"," /","|","  /","|","   /","|","    /","|","     /"]
       I£    # Only leave the first input amount of items
             #  → ["|"," /","|","  /","|"]
         R   # Reverse it
             #  → ["|","  /","|"," /","|"]
          »  # And join it by newlines
             #  → "|\n  /\n|\n /\n|"
             # (after which the result is output implicitly)
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 14 \$\endgroup\$ – Grimmy Mar 5 at 12:33
  • 1
    \$\begingroup\$ Alternative 14 (kinda cute imo). \$\endgroup\$ – Grimmy Mar 5 at 12:44
  • 1
    \$\begingroup\$ @Grimmy Oh, I like that second approach! :) Thanks (I added both). \$\endgroup\$ – Kevin Cruijssen Mar 5 at 12:58
  • 1
    \$\begingroup\$ LRDÈ*;ʒ„|/Nèú= Alter-alternative \$\endgroup\$ – Magic Octopus Urn Apr 2 at 17:45
  • \$\begingroup\$ @MagicOctopusUrn So many alternatives are possible actually. Just thought about this one as well: LRāÈ·/ā„/|sèú». I have the feeling 13 might be possible, but I'm not seeing it. \$\endgroup\$ – Kevin Cruijssen Apr 2 at 18:04
10
\$\begingroup\$

Husk, 12 bytes

↔↑ṁe"|"¡Θ" /

Try it online!

Builds the infinite triangle upside-down, then takes the required number of lines and reverses them before printing.

Explanation

↔↑ṁe"|"¡Θ" /
       ¡        Repeat and accumulate results:
        Θ          prepend a space
         " /       starting from the string " /"
                   (this will create all the lines of the slanted side)
  ṁ             For each line:
   e"|"            put it in a list with a "|" line
  ṁ             and merge all these lists together
 ↑              Take the number of lines required by the input
↔               Reverse the result
| improve this answer | |
\$\endgroup\$
8
\$\begingroup\$

Python 2, 45 bytes

def f(n):print n%2*'|'or n/2%n*' '+'/';f(n-1)

Try it online!

A function that prints, terminating with error. The %n in n/2%n is just to give an error when n falls to 0, but is harmless otherwise.


As a program

50 bytes

n=input()
while n:print n%2*'|'or n/2*' '+'/';n-=1

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Using zero-div/mod to break out of things is actually really creative and I don't think I've seen it before! Gotta keep this one in mind. \$\endgroup\$ – HyperNeutrino Mar 5 at 1:13
4
\$\begingroup\$

Haskell, 48 bytes

unlines.reverse.(`take`f" /")
f c="|":c:f(' ':c)

Try it online!

f" /" generates an infinite (reversed) approximate triangle, the first line is mostly formatting.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ This is a really really really cool solution. I think people haven't upvoted because they haven't noticed the elegance of the recursion used here... As for me, I'm still digesting it. Good job! \$\endgroup\$ – RGS Mar 6 at 22:27
4
\$\begingroup\$

brainfuck, 168 bytes

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

Try it online, with 10 as input. There is substantial room for improvement for sure. I should try different memory layouts for the constants, for example. My pointer walks around way too much.

The commented code:

Divide input by two and get the mod as well
Mem layout is
input | quotient | remainder | ifelse flag | 0
,[->>>+<[-<+>>-]>[<+>->]<<<<]
Mem: ^0 | quotient | remainder | 0 | 0
Build 32 which is the SPACE character
>>>>>>>++>++
Mem: 0 | quot | rem | 0 | 0 | 0 | 0 | 2 | ^2
[-<[-<++>]<[->++<]>>]
Mem: 0 | quot | rem | 0 | 0 | 0 | 0 | 32 | ^0
Build 124 and 47 for the vertical bar and the slash
<<
++++++[-<+++++++>]<[-<+<+++>>]++++++++++<+++++<--
Mem: 0 | quot | rem | ^124 | 47 | 10 | 0 | 32
If there is a remainder print the loose vertical bar
<[->.>>.<<<]<
Mem: 0 | ^quot | 0 | 124 | 47 | 10 | 0 | 32
while there is something in the quotient
[
  print those many spaces
[->+>>>>>.<<<<<<] print as many spaces as needed
  then a slash
>>>.
  then a newline
>.
  then a vertical bar
<<.
  then a newline
>>.<<<
reset the space counter and decrement it
[-<+>]<-
] (end while)

that you can try at a different interpreter and to which you can pass different input numbers more easily. For example, try typing \10 in the input bar. Then pass the commented code over this Python script to remove the comments and get the byte count.

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

C (gcc), 52 51 bytes

f(n){for(;n--;)printf(n&1?"%*c\n":"|\n",n/2+2,47);}

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I beat your solution by a hair. I'm surprised you didn't come up with the same thing I did. \$\endgroup\$ – S.S. Anne Mar 5 at 17:58
3
\$\begingroup\$

APL (Dyalog Unicode), 21 20 bytesSBCS

⊖(0⌊-\∘⍳)⌽⊢↑⍤0⍴∘'|/'

Try it online!

Edit: Use ↑⍤0 instead of ↑¨ to avoid an extraneous use of .

An anonymous tacit function. This is an improvement over Graham's APL+WIN solution using modern APL.

I was about to post a 24-byter when -\⍳n randomly struck my brain. It is an expression that yields first n terms of 0 -1 1 -2 2 -3 3 ..., so applying 0⌊ yields 0 -1 0 -2 0 -3 0 ... which is perfect for row-wise rotation vector.

How it works

⊖(0⌊-\∘⍳)⌽⊢↑⍤0⍴∘'|/'  ⍝ Input: n
              ⍴∘'|/'  ⍝ Repeat '|/' to length n
          ⊢↑⍤0        ⍝ Create a n-by-n matrix whose 1st column is the above
                      ⍝   and the rest is blank
         ⌽            ⍝ Rotate left each row:
 (  -\∘⍳)             ⍝   First n values of 0 -1 1 -2 2 -3 3 ...
  0⌊                  ⍝   Minimum with 0; 0 -1 0 -2 0 -3 ...
                      ⍝ (Negative rotate left is rotate right)
⊖                     ⍝ Reverse vertically
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 42 bytes

"$args"..1|%{((" "*($_/2)+"/"),"|")[$_%2]}

Try it online!

Loops from input $args down to 1, each iteration choosing whether to output spaces and a /, or the | character based on a modulo-index into an array. Default output gives us newlines for free. Ho-hum.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

J, 24 bytes

>@}.&,i.;&'|'@{.&'/'@->:

Try it online!

-4 bytes thanks to Bubbler

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 29 bytes. Nice job on the replicating matrix btw. \$\endgroup\$ – Bubbler Mar 5 at 7:55
  • \$\begingroup\$ @Bubbler thanks. I woke up with a totally new approach for 28 \$\endgroup\$ – Jonah Mar 5 at 12:51
  • \$\begingroup\$ 25, no parens. \$\endgroup\$ – Bubbler Mar 5 at 13:48
  • \$\begingroup\$ Fabulous. We're closing in on APL.... though this feels like the limit now. \$\endgroup\$ – Jonah Mar 5 at 13:53
  • \$\begingroup\$ ... And here is 24. \$\endgroup\$ – Bubbler Mar 5 at 14:27
2
\$\begingroup\$

APL+WIN, 36 33 30 bytes

3 bytes saved by incorporating bubbler's row rotation method

Prompts for integer:

    ⊖(0⌊-\⍳n)⌽(n,n)↑((n←⎕),1)⍴'|/'

Try it online! Courtesy of Dyalog Classic

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 30 bytes using excessive use of stranding and reducing m part into a train. \$\endgroup\$ – Bubbler Mar 5 at 7:58
  • \$\begingroup\$ 24 bytes as a full train, with tweaking some parts. Nice job, I couldn't find such an elegant expression without seeing your code. \$\endgroup\$ – Bubbler Mar 5 at 8:05
  • \$\begingroup\$ @Bubbler Thanks but unfortunately my ancient APL+WIN does not support chains \$\endgroup\$ – Graham Mar 5 at 8:12
  • \$\begingroup\$ Oh, didn't know that. May I post it as a separate answer then? \$\endgroup\$ – Bubbler Mar 5 at 8:13
  • \$\begingroup\$ @Bubbler Sure. I am all for showing how APL can compete with the pure golfing languages \$\endgroup\$ – Graham Mar 5 at 8:16
2
\$\begingroup\$

Python 3, 66 56 55 bytes

Saved a byte thanks to kaya3!!!

def f(n):
 if n:print((-~n//2*' '+'/','|')[n&1]);f(n-1)

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ To save one byte, you can use if instead of while, and f(n-1) instead of n-=1. \$\endgroup\$ – kaya3 Mar 5 at 23:38
  • \$\begingroup\$ @kaya3 Nice one - thanks! :-) \$\endgroup\$ – Noodle9 Mar 6 at 0:08
2
\$\begingroup\$

4, 171 bytes

3.6006260132602476031061101612026401020000127908906554819090552999940099999079098993139912214131211599141161115815500503615009816317991281750111717119502503616009199991194

Try it online!

Explanations

3.    start of code
60062 assign half ASCII of pipe
60132 space
60247 slash
60310 endl
61101 int one
61202 int two
64010 int ten
2000012 multiply half-pipe by two for a pipe
790 get input
890 while there's still input
65548 char zero
1909055 decrease input char by char zero to get result
2999940 multiply previous result by ten (to make way for current char input)
0999990 put current result
790 get input again
9 end of loop
======== At this point we already got the int n
899 while (n != 0)
3139912 2141312 1159914 mod by 2 (n-[[n/2]]*2)
1161115 check odd or even
815     if odd
500 503 61500 9 print pipe and endl
816     if even
3179912 get n/2
817 501 1171711 9 print spaces
502 503 61600 9 print slash and endl
1999911 9 get n-1, end of loop
4       end of code
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ wow i had no idea this was a language \$\endgroup\$ – don bright Mar 7 at 4:12
2
\$\begingroup\$

Java (OpenJDK 8), 88 84 bytes

x->{for(int i=x,j=i+2;i-->0;j--)System.out.printf((i%2<1?"|\n":"%"+j/2+"s\n"),"/");}

Try it online!

If Java's output methods weren't so long, I'd get close to John's R submission!

Edit:
-4 bytes thanks to @Kevin Cruijssen!
Also the link led to an older 91 bytes version, fixed that now...

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Jelly, 14 13 bytes

H⁶ṁ;”/)”|ÐoṚY

Try it online!

A monadic link taking an integer and returning a list of Jelly strings. If a single newline-separates string is needed, append Y for a cost of a byte. Thanks to @JonathanAllan for saving a byte!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ There is 4 spaces in the first line before the "/" instead of 2, and I think the newline is needed \$\endgroup\$ – Kaddath Mar 5 at 12:36
  • \$\begingroup\$ Sorry now fixed \$\endgroup\$ – Nick Kennedy Mar 5 at 14:16
  • \$\begingroup\$ Since any implicit make_range performs an int cast, mould-like, , can save a byte with halve H over :2 - TIO. \$\endgroup\$ – Jonathan Allan Mar 6 at 22:36
1
\$\begingroup\$

Charcoal, 18 bytes

Nθ↙⊘θUE⁰¦¹F⊘⊕θ«↑↑¹

Try it online! Link is to verbose version of code. Explanation:

Nθ

Input n.

↙⊘θ

Print the diagonal line of the appropriate length.

UE⁰¦¹

Space the rows out.

F⊘⊕θ«↑↑¹

Fill in the vertical line on alternate lines.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 5 -n, 36 bytes

say$_%2?$"x(1+$_/2).'/':'|'while$_--

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Jelly, 23 bytes

HĊ”|ẋż³HḞR¤” ẋ$;€”/¤ẎṚY

Try it online!

It's been a while since I've golfed in Jelly, so this answer is probably embarrassingly long.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

PHP, 76 57 bytes

for(;$a=$argn--;)echo$a%2?"|
":str_repeat(' ',$a/2)."/
";

Try it online!

I feel there should be much better but can't put my finger on it yet.. I also didn't find how to use recursive functions with PHP7 arrow notation.. well..

EDIT: Actually, a basic loop is still better for PHP than recursion

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 50 bytes

f(n){for(;n;)printf(n--%2?"|\n":"%*s/\n",n/2,"");}

Takes as input an integer n and prints a triangle. It would look more realistic and save 2 bytes if n was not divided by 2.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ "It would look more realistic and save 2 bytes if n was not divided by 2." Seems to be a compelling reason not to divide by 2. \$\endgroup\$ – Cody Gray Mar 6 at 23:39
  • 1
    \$\begingroup\$ @CodyGray The output format is restricted. I have to. \$\endgroup\$ – S.S. Anne Mar 7 at 0:00
1
\$\begingroup\$

R, 75 61 bytes

Thanks again, Giuseppe! Forgot that cat does pasting itself.

for(i in scan():1)cat(`if`(i%%2,'|',c(rep('',i/2),'/')),'\n')

Try it online!

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ 61 bytes. Neat trick with the Reduce(paste,...), though! \$\endgroup\$ – Giuseppe Mar 5 at 19:44
  • \$\begingroup\$ Also, btw, if you want to notify someone who's commented on your post, you can do @<username>. Or you can do the same with users in the (often empty) R golfing chatroom \$\endgroup\$ – Giuseppe Mar 6 at 1:59
0
\$\begingroup\$

Japt -R, 16 bytes

Çg['|'/iSp°Zz]Ãw

Try it

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

MATL, 22 bytes

:2&\w~*"@:~'|/'X@)hXhP

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Python 2, 52 bytes

i=input()
while i:print(' '*(i/2)+'/','|')[i%2];i-=1

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 48 bytes

f=n=>n?(n&1?`|
`:' '.repeat(n/2)+`/
`)+f(n-1):''

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Ruby, 44 bytes

->n{(1..n).map{[?|," "*(n/2)+?/][(n-=1)%2]}}

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

JavaScript (Node.js), 47 bytes

f=(n,s=`/
`,v=`|
`)=>--n?f(n,v,s<v?' '+s:s)+v:v

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Bash, 68 bytes

f(){ for((i=$1;i-->0;)){((i%2))&&printf %$[2+i/2]s\\n /||echo \|;};}

Try it online!

Don't golf in bash that often, so tips appreciated.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Go, 94 bytes

import."fmt"
func f(n int){for n!=0{if n%2==0{Printf("%*s/\n",n/2,"")}else{Println("|")}
n--}}

Port of my C answer.

Try it online!

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy