# The (Easy) Road to Code

## Input:

• An integer $$\n$/extract_tex], which is guaranteed to be $$\\ge3\$$. • An integer $$\d\$$, which is one of $$\[-1,0,1]\$$. ## Output: A road of size $$\n\$$, which will be in a north-west direction if $$\d=-1\$$; a north direction if $$\d=0\$$; or a north-east direction if $$\d=1\$$. The road will always be three spaces wide (or five in general if we'd include the outer borders). In addition, there will be a road separator line on the bottom section, and after that alternating while going upwards. Some examples: Input: $$\n=7, d=1\$$ Output:  / / / / / / / / / / / / / / / / / /  Input: $$\n=4, d=-1\$$ Output: \ \ \ \ \ \ \ \ \ \  ## Challenge rules: • Any amount of leading/trailing spaces and/or newlines are acceptable, as long as it prints the required road somewhere on the screen. • Instead of the options $$\[-1,0,1]\$$ you are also allowed to use the options $$\[0,1,2]\$$ or $$\[1,2,3]\$$ instead. Also, you can choose which of the three options map to which of the three directions. (Make sure to mention which options you've used if it differs from the $$\[-1,0,1]\$$ for [north-west, north, north-east] respectively that is used in this challenge description!) • Any reasonable output format is acceptable. The most common is of course to print it to STDOUT, but returning it as a string or 2D character list is fine as well. ## General rules: • This is , so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. • Default Loopholes are forbidden. • If possible, please add a link with a test for your code (i.e. TIO). • Also, adding an explanation for your answer is highly recommended. ## Test cases: The two examples above, and: Input: $$\n=10, d=0\$$ Output: | | | | | | | | | | | | | | | | | | | | | | | | |  • Alternative title: "Mad Max Code Warrior" – akozi Mar 7 at 17:08 • Isn't the first example incorrect? It has a middle strip on every odd line instead of every even line – moonheart08 Mar 7 at 17:23 • @moonheart08 No. The bottom one will always have a road separator line, whether the input is odd or even. After that it's alternating while going upwards. I've modified the text a bit to hopefully make it clearer. – Kevin Cruijssen Mar 7 at 17:41 • Oh, so i'm wrong. Alright. Thanks for clarifying. – moonheart08 Mar 7 at 17:49 ## 24 Answers # Canvas, 23 22 bytes B}⁴H‟ｍ↶⁷？／|∙/╋］＼|∙\╋］｝  Try it here! Uses the direction inputs 0, 1 and 2. Explanation: ...‟ push "--¶¶- ¶¶--" m mold the horizontal length to the 1st input - a horizontal road ↶ rotate counter-clockwise - so the separator is on the bottom also replaces the dashes with bars ⁷? ] ]} switch over the 2nd input: default case (input 2): / pad with spaces to a "/" diagonal |∙/╋ replace "|" with "/" case 0: \ pad with spaces to a "\" diagonal |∙\╋ replace "|" with "" case 1 is empty, but because of a bug, the trailing "}" is still required  • Would you mind adding an explanation? :) – Kevin Cruijssen Mar 13 at 7:27 • @KevinCruijssen added. – dzaima Mar 13 at 10:16 # Python 2, 797873 72 bytes n,d=input() c='|\/'[d] i=n while i:print' '*(n-i*d)+c,i%2*c or' ',c;i-=1  Try it online! Takes [1,0,-1] for [north-west, north, north-east] -1 byte, thanks to Neil • Jeez, what I wouldn’t give for Python-like slicing in Kotlin – Adam Mar 7 at 18:36 • i%2*c or' ' saves a byte. – Neil Mar 12 at 16:33 # Python 2, 66 bytes n,d=input() s=' '+'|\/'[d] for c in(s*n)[n:]:print' '*n+s,c+s;n+=d  Try it online! Uses d=-1 for NE, d=0 for N, and d=1 for NW. Takes advantage of leading spaces being allowed. The rule that the bottom segment of the road have a separator made it tricky to get the parity right; it's achieved by the slicing (s*n)[n:] taking the second half of the 2n alternations between space and a the road character. # 1. Python 3.5, 122 120 bytes Script takes two params: n, d. d: 0, 1, 2 -> \ | / tio.run import sys;(n,d)=[*map(int,sys.argv[1:3])];c="\\|/"[d] for i in range(n):j=n+~i;print(" "*(i,0,j)[d],c,c*(j%2<1)or" ",c)  output:  ./script.py 6 2 / / / / / / / / / / / / / / /  ./script.py 6 1 | | | | | | | | | | | | | | |  ./script.py 6 0 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \  ## Explanation # parse input params (n,d)=[*map(int,sys.argv[1:3])] # select char for "road" c="\\|/"[d] # loop n-times for i in range(n): # complement (how many lines to end) j=n+~i # print # space i or 0 or j times # road, center of road if j is even else space, road print(" "*(i,0,j)[d], c, c*(j%2<1) or " ", c)  edit: -2 bytes thanks to Kevin Cruijssen • Nice answer! :) Two small things to golf: n-1-i can be n+~i (relevant tip) and j%2==0 can be j%2<1. If you haven't seen them yet, Tips for golfing in Python and Tips for golfing in <all languages> might both be interesting to read through. – Kevin Cruijssen Mar 7 at 19:21 • Thank you :) I have'nt seen this n+~i yet, but looks helpful. Also thanks for code highlight. – Rene Mar 8 at 20:54 • You're welcome! Enjoy your stay and golfing many answers. :) Oh, and have a nice weekend. – Kevin Cruijssen Mar 9 at 13:19 • j%2*" "or c saves another couple of bytes. – Neil Mar 12 at 16:27 # PowerShell, 88828074 71 bytes -8 bytes thanks to Mazzy -6 bytes thanks to AdmBorkBork and Mazzy -3 bytes thanks to AdmBorkBork param(n,d)n..1|%{' '*(_,(n-_))[d]+(y='/\|'[d])," y"[_%2],y}  Try it online! Uses [0,1,2] for NW, NE, N. Uses d as a list index twice to first get the spacing method (Drops off the list when using 2 which returns 0) and then which character to use when drawing the lines. Appends a list to the string of spaces (which innately has spaces between the members when appended as such) which builds the road. Also swaps between an open lane or a dash based on modulo math. • 80 bytes if uses [0,1,2] for [NW,NE,N] – mazzy Mar 7 at 15:44 • @mazzy Smart. I completely forgot about intentionally falling off a list. – Veskah Mar 7 at 15:51 • Awesome idea with array.toString from AdmBorkBork! Thanks. 74 bytes – mazzy Mar 7 at 15:56 • 71 bytes by indexing the middle part into a string rather than an array. – AdmBorkBork Mar 7 at 16:01 # C (gcc), 100 90 bytes f(a,b,c,d){for(c=a,d="\\|/"[b+1];c--;)printf("%*c %c %c\n",b>0?c+1:b?a-c:0,d,c%2?32:d,d);}  Try it online! Well written version # Charcoal, 3329 23 bytes ↷ＮＮη⊘⊕ηＵＥ¹¦¹Ｆ⟦²±²⟧«Ｊι⁰η  Try it online! Link is to verbose version of code. Now that all of the underlying Charcoal bugs seem to be fixed I can advertise the optimal code. Explanation: ↶Ｎ  Rotate the cursor direction anticlockwise according to the first input, so that 1 becomes north east, 2 north and 3 north west. Ｎη  Input the length of the road. ⊘⊕ηＵＥ¹¦¹  Print half the length of the road and then stretch it giving the road separator. Ｆ⟦²±²⟧«Ｊι⁰η  Print the sides of the road. @KevinCruijssen subsequently submitted a harder version of this question which was since deleted but users with enough rep can see it here: The (Hard) Road to Code The stretching trick I used in this answer isn't applicable to that question, so instead I wrote the following 47 45-byte program: Ｆ³«Ｊ×ι⊘⊕θ⁰≔…⟦¹ ⟧⊕﹪ι²ιＦη«↶§κ⁰Ｆ⊖§κ¹§ιⅉＰ§ιⅉ↑↷§κ⁰  Try it online! Link is to verbose version of code. Explanation: Ｆ³«  Loop over the sides and separator. Ｊ×ι⊘⊕θ⁰  Jump to the start of the side. ≔…⟦¹ ⟧⊕﹪ι²ι  Make an array containing a 1 and a space, but remove the space again if we're drawing the sides rather than the separator. Ｆη«  Loop over each road section. ↶§κ⁰  Rotate the cursor direction accordingly. Ｆ⊖§κ¹  Loop over one less than the length of the road section... §ιⅉ  ... and print alternating elements of the array. The alternation is achieved by cyclically indexing into the array with the Y-coordinate of the cursor. Ｐ§ιⅉ  Print the last row of this road section, but without moving the cursor... ↑  ... so that the cursor can be moved up ready for the next section instead. ↷§κ⁰  Rotate the cursor direction back ready for the next section. # Kotlin, 96 92 bytes {n,d->val c="\\|/"[d];(0..n-1).map{println(" ".repeat(n-it*(d-1))+ "c {" c"[it%2]} c")}}  Accepts [0, 1, 2] instead of [-1, 0, 1] It works similarly to solutions in other languages, but unfortunately Kotlin doesn’t really shine in this one. val c=“\\|/“; retrieves the char to use in road building by taking advantage of the fact that Kotlin treats Strings like an Array of chars (as it should, looking at you Java) Try it online! • Hi, welcome to PPCG! There is a minor issue in your output. The altering lines in the center of the road should start with a line at the bottom for even inputs, instead of at the top. You can compare your output for 4 with my example of 4 to see the difference I mean. I don't know Kotlin that well, but I think you can solve it (and golf 4 bytes at the same time) by changing [(it+1)%2] to [it%2]. :) Apart from that it's a nice answer, so +1 from me. – Kevin Cruijssen Mar 7 at 13:46 • Awesome, thanks so much for the welcome & help! I’ll change it – Adam Mar 7 at 13:51 # TSQL code, 171 117 bytes I realized this could be written much shorter as code. DECLARE @n INT=7,@d INT=0 ,@ INT=0a:PRINT space(@n-@*@d)+stuff(replicate(substring('\|/',@d+2,1)+' ',3),3,@%2,space(@%2))SET @+=1IF @n>@ GOTO a  # TSQL query, 137 bytes USE master DECLARE @n INT=6,@ INT=-1 SELECT space(@n-y*@)+z+iif(y%2=1,z,' ')+z FROM(SELECT top(@n)row_number()over(order by @)y,' '+substring('\|/',@+2,1)z FROM spt_values)x  USE master is not necessary, if your database is master already. Some users however have a different default database. Script when trying it out is slightly different. I had to replace space ascii-32 with ascii-160, the spaces were not shown. Try it out Made some tweaks and realized that I could replace order by 1/0 with order by @ • How come order by 1/0 doesn't cause a divide by zero error? – HoneyBadger Mar 7 at 22:41 • because 1/0 is not being calculated. where exists(select 1/0) will have the same effect – t-clausen.dk Mar 7 at 22:54 • Moved my question to StackOverflow – HoneyBadger Mar 11 at 9:01 # JavaScript (ES8), 90 87 85 bytes Takes input as (direction)(length). Expects $$\0\$$ for North-West, $$\1\$$ for North or $$\2\$$ for North-East. d=>g=(n,w=n)=>n?(c='/|\\'[d]).padStart([n--,,w-n][d])+ {n&1?' ':c} {c} +g(n,w):''  Try it online! # JavaScript (ES6), 90 bytes This one draws the output character by character with a little more maths instead of the .padStart() method. Takes input as (direction)(length). Expects $$\1\$$ for North-West, $$\2\$$ for North or $$\3\$$ for North-East. d=>n=>(g=x=>y? /|\\ [x+5?17+y%2*4>>--x+5-[,n+1-y,n,y][d]&1&&d:(x=n,y--,4)]+g(x):'')(y=n)  Try it online! # Jelly, 31 30 bytes ⁶ẋẋƤḂ};€ị“\/|”ẋ3KƊ}Ṛ⁹¡⁶-2¦€ÐeṚ  A dyadic Link accepting the length on the left and the negated-direction* on the right which yields a 2d array of characters. * [north-west, north, north-east]=[1, 0, -1] Try it online! (footer calls the Link, joins with newline characters and prints the result) ### How? ⁶ẋẋƤḂ};€ị“\/|”ẋ3KƊ}Ṛ⁹¡⁶-2¦€ÐeṚ - Link: integer, L; integer, D ⁶ - space character ẋ - repeat L times } - using the right argument (D): Ḃ - mod 2 (0 if D = 0, 1 otherwise ...A would work too) Ƥ - for each prefix (of the list of spaces): ẋ - repeat (D mod 2 times) } - using the right argument (D): Ɗ - last three links as a monad: ị“\/|” - index into "\/|" (1-indexed & modular) ẋ3 - repeat three times - e.g. "\\\" K - join with spaces "\ \ \" ;€ - concatenate €ach (altered prefix with that list) ¡ - repeat action... ⁹ - ...number of times: right argument (-1 repeats 0 times) Ṛ - ...action: reverse (i.e. reverse if north-west) Ðe - for even indexes: ¦€ - sparse application for €ach... -2 - ...to indices: [-2] (the middle of the road) ⁶ - ...action: a space character Ṛ - reverse  # Python 2, 127 bytes n,d=input() c='|/\\'[d] for i in range(n):t=0if d==0else(i if d<0else n-i);print(' '*t+'{} {} {}'.format(c,' 'if i%2==0else c,c))  Try it online! First two lines taken from @TFeld. • Hi there, welcome to PPCG! I'm afraid submissions will have to be either a function taking parameters, or a full program taking arguments or input from STDIN. Snippets like you're using right now aren't allowed I'm afraid. You could add a leading D,N=input() (and use Python 2 instead of 3) to fix this. Or you could change it to a lambda function taking these two parameters. – Kevin Cruijssen Mar 7 at 12:51 • Nice solution. Got it to 122 using " ".join(..) rather ran .format – akozi Mar 7 at 17:15 • i%2*c or' ' saves a few more bytes, although I did notice that the separator is wrong for odd length roads. – Neil Mar 12 at 16:32 # Python 2, 93 bytes n,d=input();p='' while n:g='|/\\'[d];n-=1;print['',' '*n,p][d]+g+' %s '%(g,' ')[n%2]+g;p+=' '  Try it online! • Changing +' %s '+ to ,'%s', saves 2 bytes – TFeld Mar 7 at 20:58 • @TFeld In that case you might as well remove the '%s'% completely. – Neil Mar 12 at 16:28 # J, 64 bytes ' \|/'{~(_2&|*[:i.[*1 _1{~3=])|."_1((5+[){."1(5,~[)|.@]*#:@689)  Try it online! • 1 North-West • 2 North • 3 North-East Will try to golf it later # C# (Visual C# Interactive Compiler), 129107103 93 bytes a=>b=>{for(char i=a,W="/|\\"[b+1];i>0;)Write("{0,"+(a-i*b+5)+"} {1} {0}\n",W,--i%2<1?W:' ');}  -1 for north-east, 1 for north-west, 0 for north Try it online! # Red, 157 bytes func[s d][p: pick"\|/"d set[a b]reduce pick[[4 1]0[5 + s -1]]d repeat n s[print pad/left form reduce pick[[p" "p][p p p]]odd?(n + pick[1 0]odd? s)a: a + b]]  Try it online! • 1 North-West • 2 North • 3 North-East # Japt, 53 bytes W="|/\\"gV;Æ"{W} {YÉ %2?W:' } {W}"ùVÄ?V?Y+5:5:U-Y+4Ãw  Try it Online! # Swift 4.2, 112 108 bytes -4 bytes thanks to Sriotchilism O'Zaic let c=["\\","|","/"][d];(0..<n).map{print((0..<n-0*(d-1)).map{_ in" "}.joined()+c+" \(0%2==0 ?c:" ") "+c)}  [0,1,2] instead of [-1,0,1]. Try it online! ## Explanation let c=["\\","|","/"][d]  Determines the street sign to use. (I bet this can be shortened somehow) (0..<n).map{  Iterates over the length of the street. (0..<n-0*(d-1)).map{_ in" "}.joined()  Adds the spaces in front of the street. \(0%2==0 ?c:" ")"  Adds the middle sign to every other line. My very first one ☝️, I'm happy about any optimization advices. Learned mostly from that thread: Tips for golfing in Swift. • Welcome to the site! It seems like you forgot to remove the space in between in and " " in your code even though you have removed it in your examples. – Sriotchilism O'Zaic Mar 8 at 16:53 • I don't know swift but it looks like for your interpolations on the ends of the strings (\(c) in both cases). You would save bytes by just concatenating the c to the string. Try it online! – Sriotchilism O'Zaic Mar 8 at 16:58 • Thanks, you are right! saved us 3 bytes 🚀 – palme Mar 8 at 17:09 # Perl 6, 66 bytes ->\n,\d{{(' 'x-- *d%-+^n~(' ',<\ | />[d+1])[1,(n+++)%2,1])xx n}}  Try it online! Returns a list of lines. ### Explanation ->\n,\d{ } # Block taking n, d { } # Reset  variables ( )xx n # Repeat n times ' 'x # Space times -- *d # (-1,-2,-3,...) if d=1 # (0,0,0,...) if d=0 # (1,2,3,...) if d=-1 %-+^n # modulo -~n = n+1 ~ # Concat (' ',<\ | />[d+1]) # Space or line [1,(n+++)%2,1] # Alternate middle char  # Ruby, 90 bytes n,a=**.map{|i|-i.to_i} c='|\/'[a] n.upto(-1){|i|puts' '*(i*a-n)+c+' '+[' ',c][i%2]+' '+c}  Try it online! UPDATE: Thank you, Kevin, for pointing out that my original submission was missing spaces between the road edges and markers (i.e., 3-width roads instead of 5-width.) That said, there might be a shorter fix for that than c+' '+...+' '+c. Directional information: -1, 0, 1 maps to { north-west, north, north-east } Arguments: this reads command-line arguments such as 4 -1 (a four row road, slanted to the north-west). Additional note: This was tested locally with Ruby v2.6.1, and it appears that Try It Online uses Ruby v2.5.3. I have no reason to think it would not work with all other Ruby versions. • Hi there, welcome to PPCG! The directions and altering roads are correct in your output, so well done. There is just one minor error in the current output: the road should be three spaces wide instead of 1. Currently your road is ||| or |<sp>|, but it should be |<sp>|<sp>| or |<sp><sp><sp>| (where <sp> is a space). I don't know Ruby, but It seems you can solve it by changing c+[' ',c][i%2]+c to c+' '+[' ',c][i%2]+' '+c. :) – Kevin Cruijssen Mar 10 at 12:51 • Ah good catch! Thanks for pointing that out, @KevinCruijssen. – Spencer D Mar 10 at 21:44 # Java (JDK), 116 bytes d->n->{for(int c="\\|/".charAt(d),i=n;i-->0;)System.out.printf("%"+(d<1?n-i:d>1?i+1:1)+"c%2c %c%n",c,i%2<1?c:32,c);}  Try it online! Takes d as one of 0, 1 or 2. # Japt-R, 40 bytes Æ=Vg"|\\/";²i1S+iX%2?S:U)iSp[TZÊ-YY]gVÃw  Try it online! ### Explanation: Æ=Vg"|\\/";²i1S+iX%2?S:U)iSp[TZÊ-YY]gVÃw // U = road size // V = direction Æ Ã // Loop X through [0...U] = ; // Set U to: "|\\/" // "|\/" Vg // [V] ² // Double U i1 ) // Insert at index 1: S+ // " " + X%2?S:U // X%2?" ":U i // + " " i // Insert at index 0: Sp // " " repeated this many times: [TZÊ-YY] // [0,U.length - X,X] gV // [V] w // Reverse output  • There seems to be a minor mistake in the output. Currently the road separator for even inputs starts at the top instead of the bottom. Everything else looks ok, so I hope it's not too hard of a fix. – Kevin Cruijssen Mar 12 at 19:16 • @KevinCruijssen Ah, thanks for catching that. Before I update my answer, can you confirm that this solution is okay? – Oliver Mar 12 at 19:38 • Yep, that looks completely correct. :) – Kevin Cruijssen Mar 12 at 20:06 • @KevinCruijssen Added an explanation since I know you like those :P – Oliver Mar 12 at 23:15 • Thanks, appreciated. :) I indeed always like to have explanation for golfing languages. I sometimes already have trouble understanding the JavaScript answers, let alone the golfed language of JS. ;) – Kevin Cruijssen Mar 13 at 7:26 # Stax, 23 bytes ù╒←∩♂2Ωⁿ¡├∩22♀Ç○=÷â╧δÖ↑  Run and debug it Input is two integers separated by a space. The first is d. -1 specifies north-east. 0 for north. 1 for north-west. The second parameter is n. These two values will get implicitly parsed from input and placed on the input stack with n on top. Additionally d will be accessible from the stax's x register since it's the first implicitly parsed value. For example, input "1 7"  Main stack Explanation ---------- ----------- ; [7] peek from input stack m map over integers [1..n] using the rest of the program output each produced value implicitly ; [1 7] peek from input stack + [8] add .*" [8 [42 34]] 2 character string literal with codepoints 42 and 34 @ [42] get the element at the specified modular index (8) 0 [42 0] literal zero "|\/"x@ [42 0 92] get codepoint from string literal at input d (from x register) \ [42 [0 92]] make pair :B ['\ \ \ '] encode in custom base; it's binary with custom codepoints _x* ['\ \ \ ' 1] (loop variable) * (input d) ;^ ['\ \ \ ' 1 8] peek from input stack and increment % ['\ \ \ ' 1] modulus 6+ ['\ \ \ ' 7] add 6 ) [' \ \ \ '] left-pad to length  Run this one • Would you mind adding an explanation? :) – Kevin Cruijssen Mar 13 at 7:27 • @KevinCruijssen: Not at all. – recursive Mar 13 at 16:26 # perl -M5.010 -Mfeature=signatures, 97 bytes sub f(n,d){x=qw[| / \$[$d];say" "x($d<1?$_*-$d:$n-$_),$x,$",($n-$_)%2?$":$x,$",$x for 1..\$n;}