# Alternating Triangles

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

|


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

• The string has to be joined with newlines, outputting a string list is not allowed.
• Is a list of strings acceptable output from a function for this challenge? Mar 5, 2020 at 14:26
• It's an angle, not a triangle! Mar 5, 2020 at 15:08

# 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


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

• 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. Mar 5, 2020 at 1:13

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


Try it online!

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

• 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!
– RGS
Mar 6, 2020 at 22:27

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

# 05AB1E, 171413 11 bytes

L'/ú€'|I£R»


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

Explanation:

L            # Push a list in the range [1, (implicit) input]
#  i.e. 5 → [1,2,3,4,5]
#  → [" /","  /","   /","    /","     /"]
€'|     '# 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)

• 14 Mar 5, 2020 at 12:33
• Alternative 14 (kinda cute imo). Mar 5, 2020 at 12:44
• @Grimmy Oh, I like that second approach! :) Thanks (I added both). Mar 5, 2020 at 12:58
• LRDÈ*;ʒ„|/Nèú= Alter-alternative Apr 2, 2020 at 17:45
• @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. Apr 2, 2020 at 18:04

# C (gcc), 52 51 bytes

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


Try it online!

• I beat your solution by a hair. I'm surprised you didn't come up with the same thing I did. Mar 5, 2020 at 17:58

# 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


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

# J, 24 bytes

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


Try it online!

-4 bytes thanks to Bubbler

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

# 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

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

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

• To save one byte, you can use if instead of while, and f(n-1) instead of n-=1. Mar 5, 2020 at 23:38
• @kaya3 Nice one - thanks! :-) Mar 6, 2020 at 0:08

# 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

• wow i had no idea this was a language Mar 7, 2020 at 4:12

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

• 84 bytes: -2 by removing the parenthesis around (i--%2<1)?, and an additional -2 by changing the int i=x+1,j=i+1;i>1; to int i=x,j=i+2;i-->0; and the i--%2 to i%2. Mar 6, 2020 at 8:56
• Oh, and welcome to CGCC btw! If you haven't seen it yet, Tips for golfing in Java and Tips for golfing in <all languages> might both be interesting to read through. Enjoy your stay! Mar 6, 2020 at 8:57

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

• There is 4 spaces in the first line before the "/" instead of 2, and I think the newline is needed Mar 5, 2020 at 12:36
• Sorry now fixed Mar 5, 2020 at 14:16
• Since any implicit make_range performs an int cast, mould-like, ṁ, can save a byte with halve H over :2 - TIO. Mar 6, 2020 at 22:36

# Charcoal, 18 bytes

Ｎθ↙⊘θＵＥ⁰¦¹Ｆ⊘⊕θ«↑↑¹


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

Ｎθ


Input n.

↙⊘θ


Print the diagonal line of the appropriate length.

ＵＥ⁰¦¹


Space the rows out.

Ｆ⊘⊕θ«↑↑¹


Fill in the vertical line on alternate lines.

# Perl 5-n, 36 bytes

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


Try it online!

":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 # 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! • "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. Mar 6, 2020 at 23:39 • @CodyGray The output format is restricted. I have to. Mar 7, 2020 at 0:00 # 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! • 61 bytes. Neat trick with the Reduce(paste,...), though! Mar 5, 2020 at 19:44 • 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 Mar 6, 2020 at 1:59 # Japt-R, 16 bytes Çg['|'/iSp°Zz]Ãw  Try it # MATL, 22 bytes :2&\w~*"@:~'|/'X@)hXhP  Try it online! # Python 2, 52 bytes i=input() while i:print(' '*(i/2)+'/','|')[i%2];i-=1  Try it online! # JavaScript (ES6), 48 bytes f=n=>n?(n&1?| :' '.repeat(n/2)+/ )+f(n-1):''  Try it online! # Ruby, 44 bytes ->n{(1..n).map{[?|," "*(n/2)+?/][(n-=1)%2]}}  Try it online! # JavaScript (Node.js), 47 bytes f=(n,s=/ ,v=| )=>--n?f(n,v,s<v?' '+s:s)+v:v  Try it online! # 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. # 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! # Vyxalj, 15 bytes ɾ\/꘍\|?ẋf$Y?wiṘ


Try it Online!

An attempted port of the 05AB1E answer, but not really...