Make a zigzag pattern

25

2

Your task is to take in one integer input and print a zigzag pattern using slashes and backslashes.

  • The integer input determines the length of each zig and zag, as well as the number of zigs and zags
  • The pattern always starts from right to left

Test Cases

4->
   /
  /
 /
/
\
 \
  \
   \
   /
  /
 /
/
\
 \
  \
   \
2->
 /
/
\
 \
0->
1->
/
8->
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \
       /
      /
     /
    /
   /
  /
 /
/
\
 \
  \
   \
    \
     \
      \
       \

Romulus3799

Posted 2017-09-21T19:46:33.973

Reputation: 369

3Can we output an array/list of strings for each line? Are training or leading newlines or spaces allowed? – Shaggy – 2017-09-21T23:50:26.563

2Is leading whitespace okay as long as the pattern is unaffected? – Emigna – 2017-09-22T08:10:48.170

Answers

10

Charcoal, 16 10 9 bytes

FN«↖Iθ→‖T

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

Neil

Posted 2017-09-21T19:46:33.973

Reputation: 95 035

this works (Was InputNumber broken in golfy mode too?) – ASCII-only – 2017-10-04T11:29:04.813

@ASCII-only No, thus the separate links to the given succinct version and the approximate verbose version. – Neil – 2017-10-04T12:05:45.777

Oh >_> didn't look to see which link I was opening – ASCII-only – 2017-10-04T12:06:19.437

@ASCII-only Well there's only one link now ;-) – Neil – 2017-10-04T12:49:30.497

10

C (gcc), 108 102 101 98 80 76 72 bytes

  • Saved six bytes thanks to Kevin Cruijssen; removing parentheses and golfing N-n-1 to N+~n
  • Saved a byte by moving Z's incrementation into the loop condition
  • Saved three bytes by using printf("%c\n",...) instead of putchar(...) and ,puts("")
  • Saved eighteen (!) bytes thanks to HatsuPointerKun; using printf("%*s",n,""); to print n spaces instead of using a loop j;for(j=n;j--;)putchar(32); and combining both printf(...); calls
  • Saved four bytes by using printf("%*c",-~n,...); instead of printf("%*s%c",n,"",...);
  • Saved four bytes thanks to nwellnhof; moving everything inside one loop instead of two
j;f(k){for(j=0;j<k*k;j++)printf("%*c\n",j/k%2?j%k+1:k-j%k,j/k%2?92:47);}

Try it online!

Jonathan Frech

Posted 2017-09-21T19:46:33.973

Reputation: 6 681

Z,n,j;f(N){for(Z=0;Z<N;Z++)for(n=N;n--;putchar(Z%2?92:47),puts(""))for(j=Z%2?N+~n:n;j--;)putchar(32);} 102 bytes. Removed the curly brackets by putting everything inside the loops; and changed N-n-1 to N+~n. – Kevin Cruijssen – 2017-09-22T08:27:33.427

1@KevinCruijssen Thanks. Saved another byte by swapping both Z%2?...:... and replacing Z<N;Z++ with Z++<N;. – Jonathan Frech – 2017-09-22T08:37:28.690

1

You can save several bytes by using the printf magic like i did in my answer. That way you will get rid of the for loop used to print spaces. For more details, see this stack overflow answer about left padding spaces with printf

– HatsuPointerKun – 2017-09-22T09:46:41.340

@HatsuPointerKun Thanks; that is a really short way to repeat spaces in C. – Jonathan Frech – 2017-09-22T10:01:47.073

4 bytes shorter: i;f(N){for(i=0;i<N*N;i++)printf("%*c\n",i/N%2?i%N+1:N-i%N,i/N%2?92:47);}. Try it online!

– nwellnhof – 2017-09-22T13:25:04.883

@nwellnhof Thanks. I was wondering if it would be shorter in a single loop; great that it is! – Jonathan Frech – 2017-09-22T13:32:49.260

4

MATL, 17 bytes

:"GXy@o?P47}92]*c

Try it online!

Explanation

:         % Implicit input, n. Push range [1 2 ... n]
"         % For each k in that range
  G       %   Push n again
  Xy      %   Identity matrix of that size
  @       %   Push k
  o?      %   If it's odd
    P     %     Flip the matrix upside down
    47    %     Push 47 (ASCII for '/')
  }       %   Else
    92    %     Push 92 (ASCII for '\')
  ]       %   End
  *       %   Multiply each entry of the matrix by that number
  c       %   Convert to char. Char 0 is shown as space
          % Implicit end. Implicit display

Luis Mendo

Posted 2017-09-21T19:46:33.973

Reputation: 87 464

4

C# (.NET Core), 117 103 101 bytes

a=>{for(int z=a+1,e=0;e<a*a;)System.Console.WriteLine(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++));}

Try it online!

my pronoun is monicareinstate

Posted 2017-09-21T19:46:33.973

Reputation: 3 111

You can save 14 bytes like this: a=>{var o="";for(int z=a+1,e=0;e<a*a;)o+=(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++))+"\n";return o;} 103 bytes You don't need all those parenthesis; you can combine the int; and only add +"\n" once.

– Kevin Cruijssen – 2017-09-22T06:56:56.740

Oh wow, thanks! – my pronoun is monicareinstate – 2017-09-22T07:19:36.860

Hmm, you can save 2 more bytes by printing directly, instead of returning a string: a=>{for(int z=a+1,e=0;e<a*a;)System.Console.WriteLine(e++/a%2<1?"/".PadLeft(--z):@"\".PadLeft(z++));} 101 bytes

– Kevin Cruijssen – 2017-09-22T07:37:44.700

3

SOGL V0.12, 13 12 9 bytes

╝F{±↔}P}ø

Try it Here!

could be 8 bytes ╝F{±↔}P} if the 0 test-case wasn't required

Explanation:

       }   implicitly started loop repeated input times
╝            create a down-right diagonal of the input
 F           get the current looping index, 1-indexed
  {  }       that many times
   ±↔          reverse the diagonal horizontally
      P      print that
        ø  push an empty string - something to implicitly print if the loop wasn't executed

dzaima

Posted 2017-09-21T19:46:33.973

Reputation: 19 048

3

Python 2, 69 68 62 bytes

-1 byte thanks to Jonathan Frech

lambda n:[[~i,i][i/n%2]%n*' '+'/\\'[i/n%2]for i in range(n*n)]

Try it online!

Rod

Posted 2017-09-21T19:46:33.973

Reputation: 17 588

68 bytes. – Jonathan Frech – 2017-09-21T20:10:09.893

3

Mathematica, 84 90 bytes

(n=#;Grid@Array[If[Abs[n-(s=Mod[#-1,2n])-.5]==#2-.5,If[s<n,"‌​/","\\"],""]&,{n^2,n‌​}])&
  • Thank Jenny_mathy for -6 bytes.

I have no idea why \ is obviously darker than /.

enter image description here

Keyu Gan

Posted 2017-09-21T19:46:33.973

Reputation: 2 028

284 bytes (n=#;Grid@Array[If[Abs[n-(s=Mod[#-1,2n])-.5]==#2-.5,If[s<n,"/","\\"],""]&,{n^2,n}])& – J42161217 – 2017-09-22T10:52:41.477

3

Jq 1.5, 94 89 bytes

["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add

Explanation

  ["/","\\"][range($n)%2] as $s                         # for $s= / \ / \ $n times 
| range($n)                                             # for .=0 to $n-1
| [(range(if $s=="/" then $n-.-1 else . end)|" "), $s]  # form list of spaces ending with $s
| add                                                   # concatenate

Sample Run

$ jq -Mnr --argjson n 5 '["/","\\"][range($n)%2]as$s|range($n)|[(range(if$s=="/"then$n-.-1 else. end)|" "),$s]|add'
    /
   /
  /
 /
/
\
 \
  \
   \
    \
    /
   /
  /
 /
/
\
 \
  \
   \
    \
    /
   /
  /
 /
/

Try it online!

jq170727

Posted 2017-09-21T19:46:33.973

Reputation: 411

3

Java 8, 140 134 116 bytes

n->{String r="";for(int a=0,b,c;a++<n;)for(b=n;b-->0;r+=a%2>0?"/\n":"\\\n")for(c=b-n+b|-a%2;++c<b;r+=" ");return r;}

-24 bytes thanks to @Nevay.

Explanation:

Try it here.

n->{                // Method with integer parameter and String return-type
  String r="";      //  Result-String
  for(int a=0,b,c;  //  Index integers
      a++<n;)       //  Loop (1) from 0 to the input (exclusive)
    for(b=n;        //   Reset `b` to the input
        b-->0;      //   Inner loop (2) from the input to 0 (exclusive)
                    //     After every iteration: 
        r+=a%2>0?"/\n":"\\\n") 
                    //      Append either of the slashes + a new-line
      for(c=b-n+b|-a%2;++c<b;r+=" ");
                    //    Append the correct amount of spaces
                    //   End of inner loop (2) (implicit / single-line body)
                    //  End of loop (1) (implicit / single-line body)
  return r;         //  Return the result-String
}                   // End of method

Kevin Cruijssen

Posted 2017-09-21T19:46:33.973

Reputation: 67 575

1The condition of the innermost loop can be written as c-->f*(b-n-~b) (-6 bytes). – Nevay – 2017-09-22T14:31:22.747

1116 bytes: n->{String r="";for(int a=0,b,c;a++<n;)for(b=n;b-->0;r+=a%2>0?"/\n":"\\\n")for(c=b-n+b|-a%2;++c<b;r+=" ");return r;} – Nevay – 2017-09-24T14:09:47.027

3

Javascript ES8, 83 79 78 76 75 74 71 bytes

*reduced 1 byte with ES8 thanks to Shaggy

A=(m,i=0)=>i<m*m?`/\\`[x=i/m&1].padStart(x?i%m+1:m-i%m)+`
`+A(m,++i):""

Test here

DanielIndie

Posted 2017-09-21T19:46:33.973

Reputation: 1 220

whoever downvoted my solution, could you explain why? Am i missing something? – DanielIndie – 2017-09-22T12:19:33.377

2I'm not the one who downvoted, but I assume that it is because functions need to be repeatable to be valid. Yours could be fixed pretty easily by making i a default parameter. The byte count seem off as well. – Emigna – 2017-09-22T12:21:49.680

1

Adding a TIO link is always appreciated as well, so that people can easily test your solution.

– Emigna – 2017-09-22T12:23:07.230

1@Emigna fixed it (char wise and Link wise) :) – DanielIndie – 2017-09-22T13:19:10.990

174 bytes with some ES8. Also, for JS you can just use a Stack Snippet rather than TIO. – Shaggy – 2017-09-22T15:20:34.547

@Shaggy im new to StackExchange, how can i insert Stack Snippet? – DanielIndie – 2017-09-22T19:33:34.963

2

Pyth, 20 bytes

Lm+*;dbQjs<*,_y\/y\\

Try it online!

Leaky Nun

Posted 2017-09-21T19:46:33.973

Reputation: 45 011

2

PowerShell, 81 bytes

param($a)if($a){1..$a|%{((1..$a|%{" "*--$_+'\'}),($a..1|%{" "*--$_+'/'}))[$_%2]}}

Try it online!

Ugh, this is ugly. So much repeated code, plus 7 bytes required to account for 0 special case. Golfing suggestions welcome.

AdmBorkBork

Posted 2017-09-21T19:46:33.973

Reputation: 41 581

2

Pyth, 17 bytes

js<*_+RV"\/"_B*L;

Try it online: Demonstration

Explanation:

js<*_+RV"\/"_B*L;QQQ   implicit Qs at the end
              *L;Q     list with ["", " ", "  ", ..., " "*(input-1)]
            _B         bifurcate with reverse: [["" to "   "], ["   " to ""]]
     +RV"\/"           append to each one either "\" or "/": 
                       [["\", to "   \"], ["   /" to "/"]]
    _                  reverse
   *              Q    repeat input times
  <                Q   but only take the first input many
 s                     flatten the list of lists
j                      print on each line

Jakube

Posted 2017-09-21T19:46:33.973

Reputation: 21 462

2

05AB1E, 17 16 bytes

F<„/\Nèú.sNƒR}»,

Try it online!

Explanation

F                  # for N in [0 ... input-1] do
  „/\              # push the string "/\"
     Nè            # cyclically index into this string with N
 <     ú           # prepend input-1 spaces to this string
        .s         # get suffixes
          NƒR}     # reverse the list of suffixes input+1 times
              »,   # join on newline and print

Current best attempt using canvas:

F„/\Nè©53NèΛ2®ð«4Λ

Emigna

Posted 2017-09-21T19:46:33.973

Reputation: 50 798

2

Python 3: 90 Bytes 82 Bytes

lambda n:"\n".join(" "*(abs(i%(n*2)-n+i//n%2)-1)+"/\\"[i//n%2]for i in range(n*n))

Thanks to @Jonathan Frech for pointing out that print wasn't needed and that the first zig was the wrong way

Bassintag

Posted 2017-09-21T19:46:33.973

Reputation: 31

] for -> ]for. – Jonathan Frech – 2017-09-22T09:04:16.980

You do not need the print(...), a function returning a string would be valid. Also, I think your initial zig is oriented the wrong way (\ rather than /). – Jonathan Frech – 2017-09-22T09:08:28.520

@JonathanFrech Thanks! I changed it – Bassintag – 2017-09-22T09:23:25.113

1(abs(...)-1) -> ~-abs(...). – Jonathan Frech – 2017-09-22T09:26:23.197

2

C++, 92 91 bytes

-1 bytes thanks to Kevin Cruijssen

void m(int n){for(int i=0,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);}

Thanks to the power of the magic printf

HatsuPointerKun

Posted 2017-09-21T19:46:33.973

Reputation: 1 891

You can put the int i=0,j in the for-loop for(int i=0,j;i<n;++i) to save a byte. – Kevin Cruijssen – 2017-09-22T11:10:37.770

88 bytes – ceilingcat – 2019-01-10T21:33:40.920

2

Java (OpenJDK 8), 131 106 98 96 94 91 bytes

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

Try it online!

Roberto Graham

Posted 2017-09-21T19:46:33.973

Reputation: 1 305

1You can remove quite a few parentheses: i->{for(int j=0;j<i*i;System.out.printf("%"+(j/i%2<1?i-j%i+1:j%i+2)+"s",j++/i%2<1?"/\n":"\\\n"));} (98 bytes). – Nevay – 2017-09-22T14:39:30.007

2

Dyalog APL, 39 36 35 34 bytes

{↑((,⍵ ⍵⍴(⌽,⊢)⍳⍵)/¨' '),¨⍵/⍵⍴'/\'}

Try it online!

1 byte saved thanks to Zacharý

dzaima

Posted 2017-09-21T19:46:33.973

Reputation: 19 048

Dang it, beat me by one byte. You can make ⎕IO be 0, and then remove ¯1+. – Zacharý – 2017-09-24T13:41:17.080

@Zacharý I was just about to do that :p – dzaima – 2017-09-24T13:42:04.797

Oh, one more thing: (⌽,⊢)⍳⍵ instead of (⌽⍳⍵),⍳⍵ – Zacharý – 2017-09-24T13:42:50.783

@Zacharý Yeah, I'm yet to understand the tacks, tacitness and stuff that comes with that :/ – dzaima – 2017-09-24T13:46:59.187

Don't worry, I don't fully understand how trains/forks/whatever-they're-called work either. – Zacharý – 2017-09-24T13:48:48.820

1

Perl 5, 70 + 1 (-n) = 71 bytes

$n=$_**2;$_=$"x--$_.'/';say&&s% /%/ %||s%\\ % \\%||y%\\/%/\\%while$n--

Try it online!

Xcali

Posted 2017-09-21T19:46:33.973

Reputation: 7 671

1

Excel VBA, 84 83 Bytes

Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window

For i=1To[A1]:For j=1To[A1]:?IIf(i mod 2,Space([A1]-j)&"/",Space(j-1)&"\"):Next j,i

Taylor Scott

Posted 2017-09-21T19:46:33.973

Reputation: 6 709

1

Kotlin, 102 bytes

(0..q-1).map{r->if(r%2<1)q-1 downTo 0 else{0..q-1}.map{(1..it).map{print(' ')};println('/'+45*(r%2))}}

Try it online!

jrtapsell

Posted 2017-09-21T19:46:33.973

Reputation: 915

0

Jelly, 15 bytes

ḶṚ⁶ẋm0ż⁾/\x$ṁ²Y

Try it online!

Full program.

Erik the Outgolfer

Posted 2017-09-21T19:46:33.973

Reputation: 38 134

0

Haskell, 86 85 bytes

f n=take(n*n)$cycle$[(' '<$[x..n-1])++"/"|x<-[1..n]]++[(' '<$[2..x])++"\\"|x<-[1..n]]

Try it online!

Saved one byte thanks to Laikoni

Repeat a zig ++ a zag, and take the first n*n lines.

jferard

Posted 2017-09-21T19:46:33.973

Reputation: 1 764

cycle$ ... instead of cycle( ... ) saves a byte. – Laikoni – 2017-09-22T19:15:12.677

@Laikoni thanks! – jferard – 2017-09-23T07:31:47.713

0

J, 39 35 33 32 25 bytes

' /\'{~[,/@$(|.,:+:)@=@i.

Try it online!

FrownyFrog

Posted 2017-09-21T19:46:33.973

Reputation: 3 112

0

Dyalog APL, 41 40 bytes

⎕IO must be 0.

{⍪/((⌽⍵ ⍵⍴S↑'/')(⍵ ⍵⍴'\'↑⍨S←⍵+1))[2|⍳⍵]}

Try it online!

Zacharý

Posted 2017-09-21T19:46:33.973

Reputation: 5 710

0

D, 105 bytes

import std.stdio;void m(T)(T n){for(T i,j;i<n;++i)for(j=0;j<n;++j)printf("%*c\n",i%2?j+1:n-j,i%2?92:47);}

Try it online!

Lifted from HatsuPointerKun's C++ answer.

Zacharý

Posted 2017-09-21T19:46:33.973

Reputation: 5 710