कोड के लिए (आसान) सड़क


30

इनपुट:

  • एक पूर्णांक n , जो 3 होने की गारंटी है ।
  • एक पूर्णांक d , जो [1,0,1]

आउटपुट:

आकार n की एक सड़क , जो उत्तर में पश्चिम दिशा में होगी अगर d=1 ; एक उत्तर दिशा अगर d=0 ; या उत्तर-पूर्व दिशा अगर d=1 । सड़क हमेशा तीन स्थान चौड़ी होगी (या सामान्य रूप से पाँच अगर हम बाहरी सीमाएँ शामिल करेंगे)। इसके अलावा, निचले खंड पर एक सड़क विभाजक रेखा होगी, और उसके बाद ऊपर की ओर जाते हुए बारी-बारी से।

कुछ उदाहरण:

इनपुट: n=7,d=1
आउटपुट:

      / / /
     /   /
    / / /
   /   /
  / / /
 /   /
/ / /

इनपुट: n=4,d=1 आउटपुट:

\   \
 \ \ \
  \   \
   \ \ \

चुनौती नियम:

  • प्रमुख / अनुगामी स्थानों और / या न्यूलाइन्स की कोई भी राशि स्वीकार्य है, जब तक कि यह स्क्रीन पर कहीं आवश्यक सड़क को प्रिंट नहीं करता है।
  • विकल्पों के बजाय [1,0,1] आपको विकल्प [0,1,2] या [1,2,3] का उपयोग करने की भी अनुमति है । इसके अलावा, आप तीन विकल्पों में से तीन दिशाओं में से कौन सा नक्शा चुन सकते हैं। (जो विकल्प आप का उपयोग किया है उल्लेख करने के लिए अगर यह से अलग है सुनिश्चित करें [1,0,1] के लिए [north-west, north, north-east]! क्रमशः है कि इस चुनौती वर्णन में प्रयोग किया जाता है)
  • कोई भी उचित आउटपुट प्रारूप स्वीकार्य है। सबसे आम बेशक इसे STDOUT में प्रिंट करना है, लेकिन इसे एक स्ट्रिंग या 2 डी चरित्र सूची के रूप में वापस करना ठीक है।

सामान्य नियम:

  • यह , इसलिए बाइट्स जीत में सबसे छोटा जवाब है।
    कोड-गोल्फ भाषाओं को गैर-कोडगॉल्फिंग भाषाओं के साथ उत्तर पोस्ट करने से हतोत्साहित न करें। 'किसी भी' प्रोग्रामिंग भाषा के लिए यथासंभव संक्षिप्त उत्तर के साथ आने का प्रयास करें।
  • डिफ़ॉल्ट I / O नियमों के साथ आपके उत्तर के लिए मानक नियम लागू होते हैं , इसलिए आपको उचित पैरामीटर और रिटर्न-प्रकार, पूर्ण कार्यक्रमों के साथ STDIN / STDOUT, फ़ंक्शन / विधि का उपयोग करने की अनुमति है। तुम्हारा कॉल।
  • डिफ़ॉल्ट ढीले निषिद्ध हैं।
  • यदि संभव हो, तो कृपया अपने कोड (यानी TIO ) के लिए एक परीक्षण के साथ एक लिंक जोड़ें ।
  • साथ ही, आपके उत्तर के लिए स्पष्टीकरण जोड़ने की अत्यधिक अनुशंसा की जाती है।

परीक्षण के मामलों:

उपरोक्त दो उदाहरण हैं, और:

इनपुट: n=10,d=0
आउटपुट:

|   |
| | |
|   |
| | |
|   |
| | |
|   |
| | |
|   |
| | |

3
वैकल्पिक शीर्षक: "मैड मैक्स कोड वारियर"
एकोजी

1
क्या पहला उदाहरण गलत नहीं है? यह प्रत्येक विषम रेखा के बजाय प्रत्येक विषम रेखा पर एक मध्य पट्टी है
चंद्रहेट ० at

2
@ moonheart08 नहीं। नीचे हमेशा एक सड़क विभाजक रेखा होगी, चाहे इनपुट विषम हो या सम। इसके बाद यह ऊपर की ओर जाते हुए बारी-बारी से होता है। मैंने टेक्स्ट को थोड़ा संशोधित किया है ताकि उम्मीद है कि यह स्पष्ट हो सके।
केविन क्रूज़सेन

ओह, तो मैं गलत हूँ। ठीक है। स्पष्टीकरण देने के लिए धन्यवाद।
चन्द्रावत ०

जवाबों:


2

कैनवास , २३ २२ बाइट्स

B}⁴H‟m↶⁷?/|∙/╋]\|∙\╋]}

यहाँ यह कोशिश करो!

दिशा इनपुट का उपयोग करता है 0, 1 और 2।

स्पष्टीकरण:

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

क्या आप एक स्पष्टीकरण जोड़ना चाहेंगे? :)
केविन क्रूज़सेन

1
@KevinCruijssen गयी।
द्विजिमा


7

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.


6

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


3
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

1
Thank you :) I have'nt seen this n+~i yet, but looks helpful. Also thanks for code highlight.
Rene

You're welcome! Enjoy your stay and golfing many answers. :) Oh, and have a nice weekend.
Kevin Cruijssen

j%2*" "or c saves another couple of bytes.
Neil

5

PowerShell, 88 82 80 74 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.


1
80 bytes if uses [0,1,2] for [NW,NE,N]
mazzy

1
@mazzy Smart. I completely forgot about intentionally falling off a list.
Veskah

1
Awesome idea with array.toString from AdmBorkBork! Thanks. 74 bytes
mazzy

3
71 bytes by indexing the middle part into a string rather than an array.
AdmBorkBork


5

Charcoal, 33 29 23 bytes

↷NNη⊘⊕ηUE¹¦¹F⟦²±²⟧«Jι⁰η

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:

↶N

Rotate the cursor direction anticlockwise according to the first input, so that 1 becomes north east, 2 north and 3 north west.

Nη

Input the length of the road.

⊘⊕ηUE¹¦¹

Print half the length of the road and then stretch it giving the road separator.

F⟦²±²⟧«Jι⁰η

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:

F³«J×ι⊘⊕θ⁰≔…⟦¹ ⟧⊕﹪ι²ιFη«↶§κ⁰F⊖§κ¹§ιⅉP§ιⅉ↑↷§κ⁰

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

F³«

Loop over the sides and separator.

J×ι⊘⊕θ⁰

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.

Fη«

Loop over each road section.

↶§κ⁰

Rotate the cursor direction accordingly.

F⊖§κ¹

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.

P§ιⅉ

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.


4

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

Awesome, thanks so much for the welcome & help! I’ll change it
Adam

4

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 @


2
How come order by 1/0 doesn't cause a divide by zero error?
HoneyBadger

because 1/0 is not being calculated. where exists(select 1/0) will have the same effect
t-clausen.dk

Moved my question to StackOverflow
HoneyBadger

3

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!


3

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

2

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.


1
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

1
Nice solution. Got it to 122 using " ".join(..) rather ran .format
akozi

1
i%2*c or' ' saves a few more bytes, although I did notice that the separator is wrong for odd length roads.
Neil

2

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

@TFeld In that case you might as well remove the '%s'% completely.
Neil



1

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


1

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.


1
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.
Wheat Wizard

1
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!
Wheat Wizard

1
Thanks, you are right! saved us 3 bytes 🚀
palme

1

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

1

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

Ah good catch! Thanks for pointing that out, @KevinCruijssen.
Spencer D


1

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

@KevinCruijssen Ah, thanks for catching that. Before I update my answer, can you confirm that this solution is okay?
Oliver

Yep, that looks completely correct. :)
Kevin Cruijssen

1
@KevinCruijssen Added an explanation since I know you like those :P
Oliver

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

1

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

1
@KevinCruijssen: Not at all.
recursive

0

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;}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.