Slither Like a Snake Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The PPCG Site design is on its way - help us make it awesome! Sandbox for Proposed ChallengesRotate the anti-diagonalsRotate every row and column in a matrixRotate every 2x2 block in a matrixZigzagify a MatrixMaximum Maxima!Is it a stochastic matrix?Rotating a 2D MatrixSum of first row and column, then second row and column … and so onProgression of Matrix ColumnsWhere is that snake going?Is the bus load legal?

Dating a Former Employee

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

Closed form of recurrent arithmetic series summation

Is "Reachable Object" really an NP-complete problem?

How do pianists reach extremely loud dynamics?

When the Haste spell ends on a creature, do attackers have advantage against that creature?

Is there such thing as an Availability Group failover trigger?

Do wooden building fires get hotter than 600°C?

Circuit to "zoom in" on mV fluctuations of a DC signal?

How do I make this wiring inside cabinet safer? (Pic)

Compare a given version number in the form major.minor.build.patch and see if one is less than the other

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

Using audio cues to encourage good posture

What is the meaning of the new sigil in Game of Thrones Season 8 intro?

How would a mousetrap for use in space work?

Do I really need recursive chmod to restrict access to a folder?

Did MS DOS itself ever use blinking text?

What do you call the main part of a joke?

Is there a kind of relay only consumes power when switching?

Is this homebrew Lady of Pain warlock patron balanced?

Generate an RGB colour grid

Is grep documentation wrong?

What is the longest distance a player character can jump in one leap?

What are the out-of-universe reasons for the references to Toby Maguire-era Spider-Man in ITSV



Slither Like a Snake



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The PPCG Site design is on its way - help us make it awesome!
Sandbox for Proposed ChallengesRotate the anti-diagonalsRotate every row and column in a matrixRotate every 2x2 block in a matrixZigzagify a MatrixMaximum Maxima!Is it a stochastic matrix?Rotating a 2D MatrixSum of first row and column, then second row and column … and so onProgression of Matrix ColumnsWhere is that snake going?Is the bus load legal?










21












$begingroup$


The Idea



We've done matrix spirals before, and full rotations, and even diagonal
rotations,
but not, as far as I can find, snake rotations!



What is a snake rotation?



Imagine the rows of a matrix snaking back and forth, with dividers between
them like the dividers of long queue:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15|
+------------ |
20 19 18 17 16|
+--------------+


Now imagine rotating these items by 2. Each item advances, like people moving
in a line, and the items at the end spill out and return to the beginning:



 +--------------+
--> 19 20 1 2 3|
+------------ |
| 8 7 6 5 4|
| +-----------+
| 9 10 11 12 13|
+------------ |
<-- 18 17 16 15 14|
+--------------+


If there are an odd number of rows it will exit from the right, but still wrap
to the beginning. For example, here's a 3 rotation:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15
+--------------+


+--------------+
--> 13 14 15 1 2|
+------------ |
| 7 6 5 4 3|
| +-----------+
| 8 9 10 11 12 -->
+--------------+


A negative rotation will take you backwards. Here's a -2 rotation:



 +--------------+
<-- 3 4 5 6 7|
+------------ |
|12 11 10 9 8|
| +-----------+
|13 14 15 1 2 <--
+--------------+


The Challenge



Your function or program will take 2 inputs, in any convenient format:



  • A matrix

  • A integer (positive or negative) indicating how many places to rotate it.

It will return:



  • The rotated matrix

Notes:



  • Code golf. Fewest bytes wins.

  • Matrixes need not be square, but will contain at least 2 rows and 2 columns

  • Positive integers will rotate row 1 toward the right

  • Negative integers will rotate row 1 toward the left

  • You may reverse the meaning of positive / negative rotation numbers, if convenient

  • The rotation number can be larger than the number of items. In that case, it
    will wrap. That is, it will be equivalent to the number modulo the number of
    items.

  • The matrix will contain only integers, but it may contain any integers,
    including repeats

Test Cases



Format:



  • Matrix

  • Rotation number

  • Expected return value


4 5
6 7

1

6 4
7 5



2 3 4 5
6 7 8 9
10 11 12 13

-3

5 9 8 7
12 11 10 6
13 2 3 4



8 8 7 7
5 5 6 6

10

5 5 8 8
6 6 7 7









share|improve this question











$endgroup$







  • 4




    $begingroup$
    Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
    $endgroup$
    – Jonah
    Apr 14 at 1:24






  • 5




    $begingroup$
    This definitely needs an answer in Python.
    $endgroup$
    – gwaugh
    Apr 14 at 13:47















21












$begingroup$


The Idea



We've done matrix spirals before, and full rotations, and even diagonal
rotations,
but not, as far as I can find, snake rotations!



What is a snake rotation?



Imagine the rows of a matrix snaking back and forth, with dividers between
them like the dividers of long queue:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15|
+------------ |
20 19 18 17 16|
+--------------+


Now imagine rotating these items by 2. Each item advances, like people moving
in a line, and the items at the end spill out and return to the beginning:



 +--------------+
--> 19 20 1 2 3|
+------------ |
| 8 7 6 5 4|
| +-----------+
| 9 10 11 12 13|
+------------ |
<-- 18 17 16 15 14|
+--------------+


If there are an odd number of rows it will exit from the right, but still wrap
to the beginning. For example, here's a 3 rotation:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15
+--------------+


+--------------+
--> 13 14 15 1 2|
+------------ |
| 7 6 5 4 3|
| +-----------+
| 8 9 10 11 12 -->
+--------------+


A negative rotation will take you backwards. Here's a -2 rotation:



 +--------------+
<-- 3 4 5 6 7|
+------------ |
|12 11 10 9 8|
| +-----------+
|13 14 15 1 2 <--
+--------------+


The Challenge



Your function or program will take 2 inputs, in any convenient format:



  • A matrix

  • A integer (positive or negative) indicating how many places to rotate it.

It will return:



  • The rotated matrix

Notes:



  • Code golf. Fewest bytes wins.

  • Matrixes need not be square, but will contain at least 2 rows and 2 columns

  • Positive integers will rotate row 1 toward the right

  • Negative integers will rotate row 1 toward the left

  • You may reverse the meaning of positive / negative rotation numbers, if convenient

  • The rotation number can be larger than the number of items. In that case, it
    will wrap. That is, it will be equivalent to the number modulo the number of
    items.

  • The matrix will contain only integers, but it may contain any integers,
    including repeats

Test Cases



Format:



  • Matrix

  • Rotation number

  • Expected return value


4 5
6 7

1

6 4
7 5



2 3 4 5
6 7 8 9
10 11 12 13

-3

5 9 8 7
12 11 10 6
13 2 3 4



8 8 7 7
5 5 6 6

10

5 5 8 8
6 6 7 7









share|improve this question











$endgroup$







  • 4




    $begingroup$
    Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
    $endgroup$
    – Jonah
    Apr 14 at 1:24






  • 5




    $begingroup$
    This definitely needs an answer in Python.
    $endgroup$
    – gwaugh
    Apr 14 at 13:47













21












21








21


1



$begingroup$


The Idea



We've done matrix spirals before, and full rotations, and even diagonal
rotations,
but not, as far as I can find, snake rotations!



What is a snake rotation?



Imagine the rows of a matrix snaking back and forth, with dividers between
them like the dividers of long queue:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15|
+------------ |
20 19 18 17 16|
+--------------+


Now imagine rotating these items by 2. Each item advances, like people moving
in a line, and the items at the end spill out and return to the beginning:



 +--------------+
--> 19 20 1 2 3|
+------------ |
| 8 7 6 5 4|
| +-----------+
| 9 10 11 12 13|
+------------ |
<-- 18 17 16 15 14|
+--------------+


If there are an odd number of rows it will exit from the right, but still wrap
to the beginning. For example, here's a 3 rotation:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15
+--------------+


+--------------+
--> 13 14 15 1 2|
+------------ |
| 7 6 5 4 3|
| +-----------+
| 8 9 10 11 12 -->
+--------------+


A negative rotation will take you backwards. Here's a -2 rotation:



 +--------------+
<-- 3 4 5 6 7|
+------------ |
|12 11 10 9 8|
| +-----------+
|13 14 15 1 2 <--
+--------------+


The Challenge



Your function or program will take 2 inputs, in any convenient format:



  • A matrix

  • A integer (positive or negative) indicating how many places to rotate it.

It will return:



  • The rotated matrix

Notes:



  • Code golf. Fewest bytes wins.

  • Matrixes need not be square, but will contain at least 2 rows and 2 columns

  • Positive integers will rotate row 1 toward the right

  • Negative integers will rotate row 1 toward the left

  • You may reverse the meaning of positive / negative rotation numbers, if convenient

  • The rotation number can be larger than the number of items. In that case, it
    will wrap. That is, it will be equivalent to the number modulo the number of
    items.

  • The matrix will contain only integers, but it may contain any integers,
    including repeats

Test Cases



Format:



  • Matrix

  • Rotation number

  • Expected return value


4 5
6 7

1

6 4
7 5



2 3 4 5
6 7 8 9
10 11 12 13

-3

5 9 8 7
12 11 10 6
13 2 3 4



8 8 7 7
5 5 6 6

10

5 5 8 8
6 6 7 7









share|improve this question











$endgroup$




The Idea



We've done matrix spirals before, and full rotations, and even diagonal
rotations,
but not, as far as I can find, snake rotations!



What is a snake rotation?



Imagine the rows of a matrix snaking back and forth, with dividers between
them like the dividers of long queue:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15|
+------------ |
20 19 18 17 16|
+--------------+


Now imagine rotating these items by 2. Each item advances, like people moving
in a line, and the items at the end spill out and return to the beginning:



 +--------------+
--> 19 20 1 2 3|
+------------ |
| 8 7 6 5 4|
| +-----------+
| 9 10 11 12 13|
+------------ |
<-- 18 17 16 15 14|
+--------------+


If there are an odd number of rows it will exit from the right, but still wrap
to the beginning. For example, here's a 3 rotation:



 +--------------+
1 2 3 4 5|
+------------ |
|10 9 8 7 6|
| +-----------+
|11 12 13 14 15
+--------------+


+--------------+
--> 13 14 15 1 2|
+------------ |
| 7 6 5 4 3|
| +-----------+
| 8 9 10 11 12 -->
+--------------+


A negative rotation will take you backwards. Here's a -2 rotation:



 +--------------+
<-- 3 4 5 6 7|
+------------ |
|12 11 10 9 8|
| +-----------+
|13 14 15 1 2 <--
+--------------+


The Challenge



Your function or program will take 2 inputs, in any convenient format:



  • A matrix

  • A integer (positive or negative) indicating how many places to rotate it.

It will return:



  • The rotated matrix

Notes:



  • Code golf. Fewest bytes wins.

  • Matrixes need not be square, but will contain at least 2 rows and 2 columns

  • Positive integers will rotate row 1 toward the right

  • Negative integers will rotate row 1 toward the left

  • You may reverse the meaning of positive / negative rotation numbers, if convenient

  • The rotation number can be larger than the number of items. In that case, it
    will wrap. That is, it will be equivalent to the number modulo the number of
    items.

  • The matrix will contain only integers, but it may contain any integers,
    including repeats

Test Cases



Format:



  • Matrix

  • Rotation number

  • Expected return value


4 5
6 7

1

6 4
7 5



2 3 4 5
6 7 8 9
10 11 12 13

-3

5 9 8 7
12 11 10 6
13 2 3 4



8 8 7 7
5 5 6 6

10

5 5 8 8
6 6 7 7






code-golf array-manipulation matrix






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 14 at 1:28







Jonah

















asked Apr 14 at 0:23









JonahJonah

2,8161019




2,8161019







  • 4




    $begingroup$
    Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
    $endgroup$
    – Jonah
    Apr 14 at 1:24






  • 5




    $begingroup$
    This definitely needs an answer in Python.
    $endgroup$
    – gwaugh
    Apr 14 at 13:47












  • 4




    $begingroup$
    Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
    $endgroup$
    – Jonah
    Apr 14 at 1:24






  • 5




    $begingroup$
    This definitely needs an answer in Python.
    $endgroup$
    – gwaugh
    Apr 14 at 13:47







4




4




$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
Apr 14 at 1:24




$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
Apr 14 at 1:24




5




5




$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
Apr 14 at 13:47




$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
Apr 14 at 13:47










12 Answers
12






active

oldest

votes


















7












$begingroup$


Jelly, 10 bytes



UÐeẎṙṁ⁸UÐe


A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative)



Try it online!



How?



UÐeẎṙṁ⁸UÐe - Link: matrix of integers, M; integer, R
Ðe - apply to even indices of M:
U - reverse each
Ẏ - tighten
ṙ - rotate left by R
ṁ - mould like:
⁸ - chain's left argument, M
Ðe - apply to even indices:
U - reverse each





share|improve this answer











$endgroup$




















    6












    $begingroup$


    R, 121 110 101 bytes





    function(m,n,o=t(m))o)+1]=o;o[,j]=o[i,j];t(o)


    Try it online!



    Walkthrough



    function(m,n) # Input: m - matrix, n - shift
    o <- t(m) # Transpose the matrix, since R works in column-major order
    # while our snake goes in row-major order
    i <- nrow(o):1 # Take row indices in reverse
    j <- c(F,T) # Take even column indices (FALSE, TRUE, FALSE, TRUE, ...)
    o[,j] <- o[i,j] # "Normalize" the matrix by reversing every second column
    o[(seq(o)+n-1) %% # Perform the shift: add n-1 to indices,
    length(o)+1] <- o # Modulo sequence length, and +1 again
    o[,j] <- o[i,j] # Reverse even columns again to return to snake form
    t(o) # Transpose the matrix back to orginal shape and return






    share|improve this answer











    $endgroup$




















      3












      $begingroup$


      Python 3.8 (pre-releasSSSse), 119 bytes





      lambda m,r,n=-1:[[m[(k:=(j+(s:=r+i)//w)%h)][::n**k][s%w]for i in range(w:=len(m[0]))][::n**j]for j in range(h:=len(m))]


      An unnamed function accepting matrix, rotation which yields the new matrix.

      Uses the opposite rotation sign.



      Try it online!



      How?



      We set n=-1 upfront to save on parentheses later and take the matrix as m and the rotation as r.



      A new matrix is constructed with the same dimensions as m - with a width of w (w:=len(m[0])) and a height of h (h:=len(m)).



      Every other row of this matrix is reversed ([::n**j]).



      The values are looked up by calculating their row and column in the original, m using the current elements row, i, and column, j...



      We set s to r+i and k to (j+s//w)%h. k is the row of the original to access for our current element.



      In order to easily access odd indexed rows from the right we reverse such rows before accessing their elements (with [:n**k]), this means the element of interest is at s%w.






      share|improve this answer











      $endgroup$




















        3












        $begingroup$


        J, 41 30 21 bytes



        -11 bytes thanks to Jonah!



        -9 bytes thanks to FrownyFrog & ngn !



        $@]t@$(|.,@t=.|.@]/)


        Try it online!



        Reversed +/-






        share|improve this answer











        $endgroup$








        • 1




          $begingroup$
          30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
          $endgroup$
          – Jonah
          Apr 15 at 3:08











        • $begingroup$
          correction: +/- still reversed.
          $endgroup$
          – Jonah
          Apr 15 at 4:37










        • $begingroup$
          @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
          $endgroup$
          – Galen Ivanov
          2 days ago







        • 1




          $begingroup$
          21 bytes, thx @ngn
          $endgroup$
          – FrownyFrog
          2 days ago










        • $begingroup$
          @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
          $endgroup$
          – Galen Ivanov
          2 days ago


















        2












        $begingroup$


        JavaScript (Node.js), 102 bytes



        Takes input as (matrix)(integer). The meaning of the sign of the integer is inverted.





        m=>n=>(g=m=>m.map(r=>r.sort(_=>~m,m=~m)))(m.map(r=>r.map(_=>a[(l+n++%l)%l]),l=(a=g(m).flat()).length))


        Try it online!



        Helper function



        The helper function $g$ is used to 'snakify' or 'unsnakify' a matrix by reversing rows at odd indices.



        g = m => // m[] = input matrix
        m.map(r => // for each row r[] in m[]:
        r.sort(_ => // sort r[]:
        ~m, // using either 0 (don't reverse) or -1 (reverse)
        m = ~m // and toggling m before each iteration
        // (on the 1st iteration: m[] is coerced to 0, so it yields -1)
        ) // end of sort()
        ) // end of map()


        Main function



        m => n => // m[] = matrix, n = integer
        g( // invoke g on the final result
        m.map(r => // for each row r[] in m[]:
        r.map(_ => // for each entry in r[]:
        a[(l + n++ % l) % l] // get the rotated value from a[]; increment n
        ), // end of inner map()
        l = ( // l is the length of a[]:
        a = g(m).flat() // a[] is the flatten result of g(m)
        ).length // (e.g. [[1,2],[3,4]] -> [[1,2],[4,3]] -> [1,2,4,3])
        ) // end of outer map()
        ) // end of call to g





        share|improve this answer











        $endgroup$




















          2












          $begingroup$


          05AB1E, 16 bytes



          εNFR]˜²._¹gäεNFR


          Try it online!



          Thanks to Emigna for -5. Unfortunately, I can't see how to golf the redundant part out. :(






          share|improve this answer









          $endgroup$




















            1












            $begingroup$


            Charcoal, 36 bytes



            FEθ⎇﹪κ²⮌ιιFι⊞υκIE⪪Eυ§υ⁻κηL§θ⁰⎇﹪κ²⮌ιι


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



            Eθ⎇﹪κ²⮌ιι


            Reverse alternate rows of the input.



            F...Fι⊞υκ


            Flatten the array.



            Eυ§υ⁻κη


            Rotate the flattened array.



            ⪪...L§θ⁰


            Split the array back into rows.



            E...⎇﹪κ²⮌ιι


            Reverse alternate rows.



            I...


            Convert each entry to string and output in the default output format which is one number per line with rows double-spaced. (Formatting with a separator would cost the length of the separator.)






            share|improve this answer









            $endgroup$




















              1












              $begingroup$

              Pyth, 20 bytes



              L.e_W%k2bbyclQ.>syQE


              Try it online here.






              share|improve this answer









              $endgroup$




















                1












                $begingroup$


                Japt, 28 bytes



                mÏ%2©XÔªX
                c éV òUÎl
                W©UªßV1V


                Try it



                Port of Arnauld's answer. The biggest challenge was creating a reusable function. In particular, there is a helper function to reverse every other row. The approach that I am taking is to make a recursive call and depending on whether a variable is set.



                Transpiled JS:



                // U: first input argument (matrix)
                // m: map it through a function
                U = U.m(function(X, Y, Z)
                // if the row index is even, don't alter it
                // if the row index is odd, reverse it (w)
                return Y % 2 && X.w() );
                V = U
                // flatten the matrix
                .c()
                // shift by the amount specified in second argument
                .é(V)
                // partition back to matrix
                .ò(
                // the number of columns should be the same as input
                U.g().l()
                );
                // if W is specified, return the result from the first line
                W && U ||
                // otherwise, make a recursive call with the shifted matrix
                rp(V, 1, V)





                share|improve this answer











                $endgroup$




















                  1












                  $begingroup$


                  Python 3, 94 bytes





                  lambda m,n:g(roll(g(m),n))
                  g=lambda b:[b[i][::(-1)**i]for i in r_[:len(b)]]
                  from numpy import*


                  Try it online!



                  Used the odd-row-reversal from Jonathan Allan's answer.



                  lambda m,n:g(roll(g(m),n)) #reverse odd rows, shift elements, then reverse odd rows again.
                  g=lambda b:[b[i][::(-1)**i] #reverse odd rows
                  for i in r_[:len(b)]] #r_[:x] = range(x)
                  from numpy import* #roll() and r_[]





                  share|improve this answer











                  $endgroup$




















                    1












                    $begingroup$


                    APL (Dyalog Classic), 20 bytes





                    ↑∘t⊢∘⍴⍴⌽∘∊∘(t←⊢∘⌽↓)


                    Try it online!






                    share|improve this answer









                    $endgroup$




















                      1












                      $begingroup$


                      C# (Visual C# Interactive Compiler), 141 bytes





                      a=>n=>for(dynamic l=a.Length,w=a.GetLength(1),i=l,j,b=a.Clone();i-->0;)a[(j=(i+n%l+l)%l)/w,j/w%2<1?j%w:w-j%w-1]=b[i/w,i/w%2<1?i%w:w-i%w-1];


                      Try it online!



                      -5 bytes total thanks to @someone!



                      Anonymous function that performs an in-place modification to the input matrix.



                      An single loop iterates over the cells. You can scan from top to bottom and left to right using the following formulas:



                      • row=i/w

                      • col=i%w

                      Where i is a loop counter and w is the number of columns. This is varies slightly when scanning in a snake pattern.



                      • row=i/w


                      • col=i%w (0th, 2nd, 4th, etc. row)


                      • col=w-i%w-1 (1st, 3nd, 5th, etc. row)

                      Another thing to note is that the % in C# does not convert to a positive value like it does in some other languages. A couple extra bytes are needed to account for this.



                      // a: input matrix
                      // n: number of cells to rotate
                      a=>n=>
                      for(
                      // l: total number of cells
                      // w: number of columns
                      // i: loop index
                      // j: offset index
                      // b: copy of input matrix
                      dynamic
                      l=a.Length,
                      w=a.GetLength(1),
                      i=l,j,
                      b=a.Clone();
                      // iterate from i down to 0
                      i-->0;
                      )
                      // calculate the offset `j` and use
                      // the above formulas to index
                      // into `a` for setting a value
                      a[
                      (j=(i+n%l+l)%l)/w,
                      j/w%2<1?j%w:w-j%w-1
                      ]=
                      // use the un-offset index `i` and
                      // the above formulas to read a
                      // value from the input matrix
                      b[
                      i/w,
                      i/w%2<1?i%w:w-i%w-1
                      ];






                      share|improve this answer











                      $endgroup$












                      • $begingroup$
                        You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                        $endgroup$
                        – someone
                        23 hours ago










                      • $begingroup$
                        Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                        $endgroup$
                        – dana
                        20 hours ago










                      • $begingroup$
                        Get rid of y entirely to save 2 bytes: Try it online!
                        $endgroup$
                        – someone
                        16 hours ago










                      • $begingroup$
                        @someone - thanks!
                        $endgroup$
                        – dana
                        3 hours ago











                      Your Answer






                      StackExchange.ifUsing("editor", function ()
                      StackExchange.using("externalEditor", function ()
                      StackExchange.using("snippets", function ()
                      StackExchange.snippets.init();
                      );
                      );
                      , "code-snippets");

                      StackExchange.ready(function()
                      var channelOptions =
                      tags: "".split(" "),
                      id: "200"
                      ;
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function()
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled)
                      StackExchange.using("snippets", function()
                      createEditor();
                      );

                      else
                      createEditor();

                      );

                      function createEditor()
                      StackExchange.prepareEditor(
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: false,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: null,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader:
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      ,
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      );



                      );













                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f183153%2fslither-like-a-snake%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown

























                      12 Answers
                      12






                      active

                      oldest

                      votes








                      12 Answers
                      12






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      7












                      $begingroup$


                      Jelly, 10 bytes



                      UÐeẎṙṁ⁸UÐe


                      A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative)



                      Try it online!



                      How?



                      UÐeẎṙṁ⁸UÐe - Link: matrix of integers, M; integer, R
                      Ðe - apply to even indices of M:
                      U - reverse each
                      Ẏ - tighten
                      ṙ - rotate left by R
                      ṁ - mould like:
                      ⁸ - chain's left argument, M
                      Ðe - apply to even indices:
                      U - reverse each





                      share|improve this answer











                      $endgroup$

















                        7












                        $begingroup$


                        Jelly, 10 bytes



                        UÐeẎṙṁ⁸UÐe


                        A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative)



                        Try it online!



                        How?



                        UÐeẎṙṁ⁸UÐe - Link: matrix of integers, M; integer, R
                        Ðe - apply to even indices of M:
                        U - reverse each
                        Ẏ - tighten
                        ṙ - rotate left by R
                        ṁ - mould like:
                        ⁸ - chain's left argument, M
                        Ðe - apply to even indices:
                        U - reverse each





                        share|improve this answer











                        $endgroup$















                          7












                          7








                          7





                          $begingroup$


                          Jelly, 10 bytes



                          UÐeẎṙṁ⁸UÐe


                          A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative)



                          Try it online!



                          How?



                          UÐeẎṙṁ⁸UÐe - Link: matrix of integers, M; integer, R
                          Ðe - apply to even indices of M:
                          U - reverse each
                          Ẏ - tighten
                          ṙ - rotate left by R
                          ṁ - mould like:
                          ⁸ - chain's left argument, M
                          Ðe - apply to even indices:
                          U - reverse each





                          share|improve this answer











                          $endgroup$




                          Jelly, 10 bytes



                          UÐeẎṙṁ⁸UÐe


                          A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative)



                          Try it online!



                          How?



                          UÐeẎṙṁ⁸UÐe - Link: matrix of integers, M; integer, R
                          Ðe - apply to even indices of M:
                          U - reverse each
                          Ẏ - tighten
                          ṙ - rotate left by R
                          ṁ - mould like:
                          ⁸ - chain's left argument, M
                          Ðe - apply to even indices:
                          U - reverse each






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Apr 14 at 14:06

























                          answered Apr 14 at 1:22









                          Jonathan AllanJonathan Allan

                          54.5k537174




                          54.5k537174





















                              6












                              $begingroup$


                              R, 121 110 101 bytes





                              function(m,n,o=t(m))o)+1]=o;o[,j]=o[i,j];t(o)


                              Try it online!



                              Walkthrough



                              function(m,n) # Input: m - matrix, n - shift
                              o <- t(m) # Transpose the matrix, since R works in column-major order
                              # while our snake goes in row-major order
                              i <- nrow(o):1 # Take row indices in reverse
                              j <- c(F,T) # Take even column indices (FALSE, TRUE, FALSE, TRUE, ...)
                              o[,j] <- o[i,j] # "Normalize" the matrix by reversing every second column
                              o[(seq(o)+n-1) %% # Perform the shift: add n-1 to indices,
                              length(o)+1] <- o # Modulo sequence length, and +1 again
                              o[,j] <- o[i,j] # Reverse even columns again to return to snake form
                              t(o) # Transpose the matrix back to orginal shape and return






                              share|improve this answer











                              $endgroup$

















                                6












                                $begingroup$


                                R, 121 110 101 bytes





                                function(m,n,o=t(m))o)+1]=o;o[,j]=o[i,j];t(o)


                                Try it online!



                                Walkthrough



                                function(m,n) # Input: m - matrix, n - shift
                                o <- t(m) # Transpose the matrix, since R works in column-major order
                                # while our snake goes in row-major order
                                i <- nrow(o):1 # Take row indices in reverse
                                j <- c(F,T) # Take even column indices (FALSE, TRUE, FALSE, TRUE, ...)
                                o[,j] <- o[i,j] # "Normalize" the matrix by reversing every second column
                                o[(seq(o)+n-1) %% # Perform the shift: add n-1 to indices,
                                length(o)+1] <- o # Modulo sequence length, and +1 again
                                o[,j] <- o[i,j] # Reverse even columns again to return to snake form
                                t(o) # Transpose the matrix back to orginal shape and return






                                share|improve this answer











                                $endgroup$















                                  6












                                  6








                                  6





                                  $begingroup$


                                  R, 121 110 101 bytes





                                  function(m,n,o=t(m))o)+1]=o;o[,j]=o[i,j];t(o)


                                  Try it online!



                                  Walkthrough



                                  function(m,n) # Input: m - matrix, n - shift
                                  o <- t(m) # Transpose the matrix, since R works in column-major order
                                  # while our snake goes in row-major order
                                  i <- nrow(o):1 # Take row indices in reverse
                                  j <- c(F,T) # Take even column indices (FALSE, TRUE, FALSE, TRUE, ...)
                                  o[,j] <- o[i,j] # "Normalize" the matrix by reversing every second column
                                  o[(seq(o)+n-1) %% # Perform the shift: add n-1 to indices,
                                  length(o)+1] <- o # Modulo sequence length, and +1 again
                                  o[,j] <- o[i,j] # Reverse even columns again to return to snake form
                                  t(o) # Transpose the matrix back to orginal shape and return






                                  share|improve this answer











                                  $endgroup$




                                  R, 121 110 101 bytes





                                  function(m,n,o=t(m))o)+1]=o;o[,j]=o[i,j];t(o)


                                  Try it online!



                                  Walkthrough



                                  function(m,n) # Input: m - matrix, n - shift
                                  o <- t(m) # Transpose the matrix, since R works in column-major order
                                  # while our snake goes in row-major order
                                  i <- nrow(o):1 # Take row indices in reverse
                                  j <- c(F,T) # Take even column indices (FALSE, TRUE, FALSE, TRUE, ...)
                                  o[,j] <- o[i,j] # "Normalize" the matrix by reversing every second column
                                  o[(seq(o)+n-1) %% # Perform the shift: add n-1 to indices,
                                  length(o)+1] <- o # Modulo sequence length, and +1 again
                                  o[,j] <- o[i,j] # Reverse even columns again to return to snake form
                                  t(o) # Transpose the matrix back to orginal shape and return







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Apr 14 at 14:14

























                                  answered Apr 14 at 8:55









                                  Kirill L.Kirill L.

                                  6,3281529




                                  6,3281529





















                                      3












                                      $begingroup$


                                      Python 3.8 (pre-releasSSSse), 119 bytes





                                      lambda m,r,n=-1:[[m[(k:=(j+(s:=r+i)//w)%h)][::n**k][s%w]for i in range(w:=len(m[0]))][::n**j]for j in range(h:=len(m))]


                                      An unnamed function accepting matrix, rotation which yields the new matrix.

                                      Uses the opposite rotation sign.



                                      Try it online!



                                      How?



                                      We set n=-1 upfront to save on parentheses later and take the matrix as m and the rotation as r.



                                      A new matrix is constructed with the same dimensions as m - with a width of w (w:=len(m[0])) and a height of h (h:=len(m)).



                                      Every other row of this matrix is reversed ([::n**j]).



                                      The values are looked up by calculating their row and column in the original, m using the current elements row, i, and column, j...



                                      We set s to r+i and k to (j+s//w)%h. k is the row of the original to access for our current element.



                                      In order to easily access odd indexed rows from the right we reverse such rows before accessing their elements (with [:n**k]), this means the element of interest is at s%w.






                                      share|improve this answer











                                      $endgroup$

















                                        3












                                        $begingroup$


                                        Python 3.8 (pre-releasSSSse), 119 bytes





                                        lambda m,r,n=-1:[[m[(k:=(j+(s:=r+i)//w)%h)][::n**k][s%w]for i in range(w:=len(m[0]))][::n**j]for j in range(h:=len(m))]


                                        An unnamed function accepting matrix, rotation which yields the new matrix.

                                        Uses the opposite rotation sign.



                                        Try it online!



                                        How?



                                        We set n=-1 upfront to save on parentheses later and take the matrix as m and the rotation as r.



                                        A new matrix is constructed with the same dimensions as m - with a width of w (w:=len(m[0])) and a height of h (h:=len(m)).



                                        Every other row of this matrix is reversed ([::n**j]).



                                        The values are looked up by calculating their row and column in the original, m using the current elements row, i, and column, j...



                                        We set s to r+i and k to (j+s//w)%h. k is the row of the original to access for our current element.



                                        In order to easily access odd indexed rows from the right we reverse such rows before accessing their elements (with [:n**k]), this means the element of interest is at s%w.






                                        share|improve this answer











                                        $endgroup$















                                          3












                                          3








                                          3





                                          $begingroup$


                                          Python 3.8 (pre-releasSSSse), 119 bytes





                                          lambda m,r,n=-1:[[m[(k:=(j+(s:=r+i)//w)%h)][::n**k][s%w]for i in range(w:=len(m[0]))][::n**j]for j in range(h:=len(m))]


                                          An unnamed function accepting matrix, rotation which yields the new matrix.

                                          Uses the opposite rotation sign.



                                          Try it online!



                                          How?



                                          We set n=-1 upfront to save on parentheses later and take the matrix as m and the rotation as r.



                                          A new matrix is constructed with the same dimensions as m - with a width of w (w:=len(m[0])) and a height of h (h:=len(m)).



                                          Every other row of this matrix is reversed ([::n**j]).



                                          The values are looked up by calculating their row and column in the original, m using the current elements row, i, and column, j...



                                          We set s to r+i and k to (j+s//w)%h. k is the row of the original to access for our current element.



                                          In order to easily access odd indexed rows from the right we reverse such rows before accessing their elements (with [:n**k]), this means the element of interest is at s%w.






                                          share|improve this answer











                                          $endgroup$




                                          Python 3.8 (pre-releasSSSse), 119 bytes





                                          lambda m,r,n=-1:[[m[(k:=(j+(s:=r+i)//w)%h)][::n**k][s%w]for i in range(w:=len(m[0]))][::n**j]for j in range(h:=len(m))]


                                          An unnamed function accepting matrix, rotation which yields the new matrix.

                                          Uses the opposite rotation sign.



                                          Try it online!



                                          How?



                                          We set n=-1 upfront to save on parentheses later and take the matrix as m and the rotation as r.



                                          A new matrix is constructed with the same dimensions as m - with a width of w (w:=len(m[0])) and a height of h (h:=len(m)).



                                          Every other row of this matrix is reversed ([::n**j]).



                                          The values are looked up by calculating their row and column in the original, m using the current elements row, i, and column, j...



                                          We set s to r+i and k to (j+s//w)%h. k is the row of the original to access for our current element.



                                          In order to easily access odd indexed rows from the right we reverse such rows before accessing their elements (with [:n**k]), this means the element of interest is at s%w.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Apr 14 at 17:42

























                                          answered Apr 14 at 17:12









                                          Jonathan AllanJonathan Allan

                                          54.5k537174




                                          54.5k537174





















                                              3












                                              $begingroup$


                                              J, 41 30 21 bytes



                                              -11 bytes thanks to Jonah!



                                              -9 bytes thanks to FrownyFrog & ngn !



                                              $@]t@$(|.,@t=.|.@]/)


                                              Try it online!



                                              Reversed +/-






                                              share|improve this answer











                                              $endgroup$








                                              • 1




                                                $begingroup$
                                                30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 3:08











                                              • $begingroup$
                                                correction: +/- still reversed.
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 4:37










                                              • $begingroup$
                                                @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago







                                              • 1




                                                $begingroup$
                                                21 bytes, thx @ngn
                                                $endgroup$
                                                – FrownyFrog
                                                2 days ago










                                              • $begingroup$
                                                @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago















                                              3












                                              $begingroup$


                                              J, 41 30 21 bytes



                                              -11 bytes thanks to Jonah!



                                              -9 bytes thanks to FrownyFrog & ngn !



                                              $@]t@$(|.,@t=.|.@]/)


                                              Try it online!



                                              Reversed +/-






                                              share|improve this answer











                                              $endgroup$








                                              • 1




                                                $begingroup$
                                                30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 3:08











                                              • $begingroup$
                                                correction: +/- still reversed.
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 4:37










                                              • $begingroup$
                                                @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago







                                              • 1




                                                $begingroup$
                                                21 bytes, thx @ngn
                                                $endgroup$
                                                – FrownyFrog
                                                2 days ago










                                              • $begingroup$
                                                @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago













                                              3












                                              3








                                              3





                                              $begingroup$


                                              J, 41 30 21 bytes



                                              -11 bytes thanks to Jonah!



                                              -9 bytes thanks to FrownyFrog & ngn !



                                              $@]t@$(|.,@t=.|.@]/)


                                              Try it online!



                                              Reversed +/-






                                              share|improve this answer











                                              $endgroup$




                                              J, 41 30 21 bytes



                                              -11 bytes thanks to Jonah!



                                              -9 bytes thanks to FrownyFrog & ngn !



                                              $@]t@$(|.,@t=.|.@]/)


                                              Try it online!



                                              Reversed +/-







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited 2 days ago

























                                              answered Apr 14 at 18:57









                                              Galen IvanovGalen Ivanov

                                              7,53211034




                                              7,53211034







                                              • 1




                                                $begingroup$
                                                30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 3:08











                                              • $begingroup$
                                                correction: +/- still reversed.
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 4:37










                                              • $begingroup$
                                                @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago







                                              • 1




                                                $begingroup$
                                                21 bytes, thx @ngn
                                                $endgroup$
                                                – FrownyFrog
                                                2 days ago










                                              • $begingroup$
                                                @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago












                                              • 1




                                                $begingroup$
                                                30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 3:08











                                              • $begingroup$
                                                correction: +/- still reversed.
                                                $endgroup$
                                                – Jonah
                                                Apr 15 at 4:37










                                              • $begingroup$
                                                @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago







                                              • 1




                                                $begingroup$
                                                21 bytes, thx @ngn
                                                $endgroup$
                                                – FrownyFrog
                                                2 days ago










                                              • $begingroup$
                                                @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
                                                $endgroup$
                                                – Galen Ivanov
                                                2 days ago







                                              1




                                              1




                                              $begingroup$
                                              30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
                                              $endgroup$
                                              – Jonah
                                              Apr 15 at 3:08





                                              $begingroup$
                                              30 bytes, +/- not reversed, but still uses helper: $@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)
                                              $endgroup$
                                              – Jonah
                                              Apr 15 at 3:08













                                              $begingroup$
                                              correction: +/- still reversed.
                                              $endgroup$
                                              – Jonah
                                              Apr 15 at 4:37




                                              $begingroup$
                                              correction: +/- still reversed.
                                              $endgroup$
                                              – Jonah
                                              Apr 15 at 4:37












                                              $begingroup$
                                              @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
                                              $endgroup$
                                              – Galen Ivanov
                                              2 days ago





                                              $begingroup$
                                              @Jonah Now that's J! I remember seeing you applying the same trick with the alternating reversal recently, but apparently have forgotten about it. Thank you! When trying &. I was loosing the left argument all the time, that's why I gave up.
                                              $endgroup$
                                              – Galen Ivanov
                                              2 days ago





                                              1




                                              1




                                              $begingroup$
                                              21 bytes, thx @ngn
                                              $endgroup$
                                              – FrownyFrog
                                              2 days ago




                                              $begingroup$
                                              21 bytes, thx @ngn
                                              $endgroup$
                                              – FrownyFrog
                                              2 days ago












                                              $begingroup$
                                              @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
                                              $endgroup$
                                              – Galen Ivanov
                                              2 days ago




                                              $begingroup$
                                              @FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
                                              $endgroup$
                                              – Galen Ivanov
                                              2 days ago











                                              2












                                              $begingroup$


                                              JavaScript (Node.js), 102 bytes



                                              Takes input as (matrix)(integer). The meaning of the sign of the integer is inverted.





                                              m=>n=>(g=m=>m.map(r=>r.sort(_=>~m,m=~m)))(m.map(r=>r.map(_=>a[(l+n++%l)%l]),l=(a=g(m).flat()).length))


                                              Try it online!



                                              Helper function



                                              The helper function $g$ is used to 'snakify' or 'unsnakify' a matrix by reversing rows at odd indices.



                                              g = m => // m[] = input matrix
                                              m.map(r => // for each row r[] in m[]:
                                              r.sort(_ => // sort r[]:
                                              ~m, // using either 0 (don't reverse) or -1 (reverse)
                                              m = ~m // and toggling m before each iteration
                                              // (on the 1st iteration: m[] is coerced to 0, so it yields -1)
                                              ) // end of sort()
                                              ) // end of map()


                                              Main function



                                              m => n => // m[] = matrix, n = integer
                                              g( // invoke g on the final result
                                              m.map(r => // for each row r[] in m[]:
                                              r.map(_ => // for each entry in r[]:
                                              a[(l + n++ % l) % l] // get the rotated value from a[]; increment n
                                              ), // end of inner map()
                                              l = ( // l is the length of a[]:
                                              a = g(m).flat() // a[] is the flatten result of g(m)
                                              ).length // (e.g. [[1,2],[3,4]] -> [[1,2],[4,3]] -> [1,2,4,3])
                                              ) // end of outer map()
                                              ) // end of call to g





                                              share|improve this answer











                                              $endgroup$

















                                                2












                                                $begingroup$


                                                JavaScript (Node.js), 102 bytes



                                                Takes input as (matrix)(integer). The meaning of the sign of the integer is inverted.





                                                m=>n=>(g=m=>m.map(r=>r.sort(_=>~m,m=~m)))(m.map(r=>r.map(_=>a[(l+n++%l)%l]),l=(a=g(m).flat()).length))


                                                Try it online!



                                                Helper function



                                                The helper function $g$ is used to 'snakify' or 'unsnakify' a matrix by reversing rows at odd indices.



                                                g = m => // m[] = input matrix
                                                m.map(r => // for each row r[] in m[]:
                                                r.sort(_ => // sort r[]:
                                                ~m, // using either 0 (don't reverse) or -1 (reverse)
                                                m = ~m // and toggling m before each iteration
                                                // (on the 1st iteration: m[] is coerced to 0, so it yields -1)
                                                ) // end of sort()
                                                ) // end of map()


                                                Main function



                                                m => n => // m[] = matrix, n = integer
                                                g( // invoke g on the final result
                                                m.map(r => // for each row r[] in m[]:
                                                r.map(_ => // for each entry in r[]:
                                                a[(l + n++ % l) % l] // get the rotated value from a[]; increment n
                                                ), // end of inner map()
                                                l = ( // l is the length of a[]:
                                                a = g(m).flat() // a[] is the flatten result of g(m)
                                                ).length // (e.g. [[1,2],[3,4]] -> [[1,2],[4,3]] -> [1,2,4,3])
                                                ) // end of outer map()
                                                ) // end of call to g





                                                share|improve this answer











                                                $endgroup$















                                                  2












                                                  2








                                                  2





                                                  $begingroup$


                                                  JavaScript (Node.js), 102 bytes



                                                  Takes input as (matrix)(integer). The meaning of the sign of the integer is inverted.





                                                  m=>n=>(g=m=>m.map(r=>r.sort(_=>~m,m=~m)))(m.map(r=>r.map(_=>a[(l+n++%l)%l]),l=(a=g(m).flat()).length))


                                                  Try it online!



                                                  Helper function



                                                  The helper function $g$ is used to 'snakify' or 'unsnakify' a matrix by reversing rows at odd indices.



                                                  g = m => // m[] = input matrix
                                                  m.map(r => // for each row r[] in m[]:
                                                  r.sort(_ => // sort r[]:
                                                  ~m, // using either 0 (don't reverse) or -1 (reverse)
                                                  m = ~m // and toggling m before each iteration
                                                  // (on the 1st iteration: m[] is coerced to 0, so it yields -1)
                                                  ) // end of sort()
                                                  ) // end of map()


                                                  Main function



                                                  m => n => // m[] = matrix, n = integer
                                                  g( // invoke g on the final result
                                                  m.map(r => // for each row r[] in m[]:
                                                  r.map(_ => // for each entry in r[]:
                                                  a[(l + n++ % l) % l] // get the rotated value from a[]; increment n
                                                  ), // end of inner map()
                                                  l = ( // l is the length of a[]:
                                                  a = g(m).flat() // a[] is the flatten result of g(m)
                                                  ).length // (e.g. [[1,2],[3,4]] -> [[1,2],[4,3]] -> [1,2,4,3])
                                                  ) // end of outer map()
                                                  ) // end of call to g





                                                  share|improve this answer











                                                  $endgroup$




                                                  JavaScript (Node.js), 102 bytes



                                                  Takes input as (matrix)(integer). The meaning of the sign of the integer is inverted.





                                                  m=>n=>(g=m=>m.map(r=>r.sort(_=>~m,m=~m)))(m.map(r=>r.map(_=>a[(l+n++%l)%l]),l=(a=g(m).flat()).length))


                                                  Try it online!



                                                  Helper function



                                                  The helper function $g$ is used to 'snakify' or 'unsnakify' a matrix by reversing rows at odd indices.



                                                  g = m => // m[] = input matrix
                                                  m.map(r => // for each row r[] in m[]:
                                                  r.sort(_ => // sort r[]:
                                                  ~m, // using either 0 (don't reverse) or -1 (reverse)
                                                  m = ~m // and toggling m before each iteration
                                                  // (on the 1st iteration: m[] is coerced to 0, so it yields -1)
                                                  ) // end of sort()
                                                  ) // end of map()


                                                  Main function



                                                  m => n => // m[] = matrix, n = integer
                                                  g( // invoke g on the final result
                                                  m.map(r => // for each row r[] in m[]:
                                                  r.map(_ => // for each entry in r[]:
                                                  a[(l + n++ % l) % l] // get the rotated value from a[]; increment n
                                                  ), // end of inner map()
                                                  l = ( // l is the length of a[]:
                                                  a = g(m).flat() // a[] is the flatten result of g(m)
                                                  ).length // (e.g. [[1,2],[3,4]] -> [[1,2],[4,3]] -> [1,2,4,3])
                                                  ) // end of outer map()
                                                  ) // end of call to g






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Apr 14 at 8:44

























                                                  answered Apr 14 at 8:20









                                                  ArnauldArnauld

                                                  81.5k797336




                                                  81.5k797336





















                                                      2












                                                      $begingroup$


                                                      05AB1E, 16 bytes



                                                      εNFR]˜²._¹gäεNFR


                                                      Try it online!



                                                      Thanks to Emigna for -5. Unfortunately, I can't see how to golf the redundant part out. :(






                                                      share|improve this answer









                                                      $endgroup$

















                                                        2












                                                        $begingroup$


                                                        05AB1E, 16 bytes



                                                        εNFR]˜²._¹gäεNFR


                                                        Try it online!



                                                        Thanks to Emigna for -5. Unfortunately, I can't see how to golf the redundant part out. :(






                                                        share|improve this answer









                                                        $endgroup$















                                                          2












                                                          2








                                                          2





                                                          $begingroup$


                                                          05AB1E, 16 bytes



                                                          εNFR]˜²._¹gäεNFR


                                                          Try it online!



                                                          Thanks to Emigna for -5. Unfortunately, I can't see how to golf the redundant part out. :(






                                                          share|improve this answer









                                                          $endgroup$




                                                          05AB1E, 16 bytes



                                                          εNFR]˜²._¹gäεNFR


                                                          Try it online!



                                                          Thanks to Emigna for -5. Unfortunately, I can't see how to golf the redundant part out. :(







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered 2 days ago









                                                          Erik the OutgolferErik the Outgolfer

                                                          33.1k429106




                                                          33.1k429106





















                                                              1












                                                              $begingroup$


                                                              Charcoal, 36 bytes



                                                              FEθ⎇﹪κ²⮌ιιFι⊞υκIE⪪Eυ§υ⁻κηL§θ⁰⎇﹪κ²⮌ιι


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



                                                              Eθ⎇﹪κ²⮌ιι


                                                              Reverse alternate rows of the input.



                                                              F...Fι⊞υκ


                                                              Flatten the array.



                                                              Eυ§υ⁻κη


                                                              Rotate the flattened array.



                                                              ⪪...L§θ⁰


                                                              Split the array back into rows.



                                                              E...⎇﹪κ²⮌ιι


                                                              Reverse alternate rows.



                                                              I...


                                                              Convert each entry to string and output in the default output format which is one number per line with rows double-spaced. (Formatting with a separator would cost the length of the separator.)






                                                              share|improve this answer









                                                              $endgroup$

















                                                                1












                                                                $begingroup$


                                                                Charcoal, 36 bytes



                                                                FEθ⎇﹪κ²⮌ιιFι⊞υκIE⪪Eυ§υ⁻κηL§θ⁰⎇﹪κ²⮌ιι


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



                                                                Eθ⎇﹪κ²⮌ιι


                                                                Reverse alternate rows of the input.



                                                                F...Fι⊞υκ


                                                                Flatten the array.



                                                                Eυ§υ⁻κη


                                                                Rotate the flattened array.



                                                                ⪪...L§θ⁰


                                                                Split the array back into rows.



                                                                E...⎇﹪κ²⮌ιι


                                                                Reverse alternate rows.



                                                                I...


                                                                Convert each entry to string and output in the default output format which is one number per line with rows double-spaced. (Formatting with a separator would cost the length of the separator.)






                                                                share|improve this answer









                                                                $endgroup$















                                                                  1












                                                                  1








                                                                  1





                                                                  $begingroup$


                                                                  Charcoal, 36 bytes



                                                                  FEθ⎇﹪κ²⮌ιιFι⊞υκIE⪪Eυ§υ⁻κηL§θ⁰⎇﹪κ²⮌ιι


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



                                                                  Eθ⎇﹪κ²⮌ιι


                                                                  Reverse alternate rows of the input.



                                                                  F...Fι⊞υκ


                                                                  Flatten the array.



                                                                  Eυ§υ⁻κη


                                                                  Rotate the flattened array.



                                                                  ⪪...L§θ⁰


                                                                  Split the array back into rows.



                                                                  E...⎇﹪κ²⮌ιι


                                                                  Reverse alternate rows.



                                                                  I...


                                                                  Convert each entry to string and output in the default output format which is one number per line with rows double-spaced. (Formatting with a separator would cost the length of the separator.)






                                                                  share|improve this answer









                                                                  $endgroup$




                                                                  Charcoal, 36 bytes



                                                                  FEθ⎇﹪κ²⮌ιιFι⊞υκIE⪪Eυ§υ⁻κηL§θ⁰⎇﹪κ²⮌ιι


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



                                                                  Eθ⎇﹪κ²⮌ιι


                                                                  Reverse alternate rows of the input.



                                                                  F...Fι⊞υκ


                                                                  Flatten the array.



                                                                  Eυ§υ⁻κη


                                                                  Rotate the flattened array.



                                                                  ⪪...L§θ⁰


                                                                  Split the array back into rows.



                                                                  E...⎇﹪κ²⮌ιι


                                                                  Reverse alternate rows.



                                                                  I...


                                                                  Convert each entry to string and output in the default output format which is one number per line with rows double-spaced. (Formatting with a separator would cost the length of the separator.)







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Apr 14 at 9:13









                                                                  NeilNeil

                                                                  83k745179




                                                                  83k745179





















                                                                      1












                                                                      $begingroup$

                                                                      Pyth, 20 bytes



                                                                      L.e_W%k2bbyclQ.>syQE


                                                                      Try it online here.






                                                                      share|improve this answer









                                                                      $endgroup$

















                                                                        1












                                                                        $begingroup$

                                                                        Pyth, 20 bytes



                                                                        L.e_W%k2bbyclQ.>syQE


                                                                        Try it online here.






                                                                        share|improve this answer









                                                                        $endgroup$















                                                                          1












                                                                          1








                                                                          1





                                                                          $begingroup$

                                                                          Pyth, 20 bytes



                                                                          L.e_W%k2bbyclQ.>syQE


                                                                          Try it online here.






                                                                          share|improve this answer









                                                                          $endgroup$



                                                                          Pyth, 20 bytes



                                                                          L.e_W%k2bbyclQ.>syQE


                                                                          Try it online here.







                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered 2 days ago









                                                                          SokSok

                                                                          4,237925




                                                                          4,237925





















                                                                              1












                                                                              $begingroup$


                                                                              Japt, 28 bytes



                                                                              mÏ%2©XÔªX
                                                                              c éV òUÎl
                                                                              W©UªßV1V


                                                                              Try it



                                                                              Port of Arnauld's answer. The biggest challenge was creating a reusable function. In particular, there is a helper function to reverse every other row. The approach that I am taking is to make a recursive call and depending on whether a variable is set.



                                                                              Transpiled JS:



                                                                              // U: first input argument (matrix)
                                                                              // m: map it through a function
                                                                              U = U.m(function(X, Y, Z)
                                                                              // if the row index is even, don't alter it
                                                                              // if the row index is odd, reverse it (w)
                                                                              return Y % 2 && X.w() );
                                                                              V = U
                                                                              // flatten the matrix
                                                                              .c()
                                                                              // shift by the amount specified in second argument
                                                                              .é(V)
                                                                              // partition back to matrix
                                                                              .ò(
                                                                              // the number of columns should be the same as input
                                                                              U.g().l()
                                                                              );
                                                                              // if W is specified, return the result from the first line
                                                                              W && U ||
                                                                              // otherwise, make a recursive call with the shifted matrix
                                                                              rp(V, 1, V)





                                                                              share|improve this answer











                                                                              $endgroup$

















                                                                                1












                                                                                $begingroup$


                                                                                Japt, 28 bytes



                                                                                mÏ%2©XÔªX
                                                                                c éV òUÎl
                                                                                W©UªßV1V


                                                                                Try it



                                                                                Port of Arnauld's answer. The biggest challenge was creating a reusable function. In particular, there is a helper function to reverse every other row. The approach that I am taking is to make a recursive call and depending on whether a variable is set.



                                                                                Transpiled JS:



                                                                                // U: first input argument (matrix)
                                                                                // m: map it through a function
                                                                                U = U.m(function(X, Y, Z)
                                                                                // if the row index is even, don't alter it
                                                                                // if the row index is odd, reverse it (w)
                                                                                return Y % 2 && X.w() );
                                                                                V = U
                                                                                // flatten the matrix
                                                                                .c()
                                                                                // shift by the amount specified in second argument
                                                                                .é(V)
                                                                                // partition back to matrix
                                                                                .ò(
                                                                                // the number of columns should be the same as input
                                                                                U.g().l()
                                                                                );
                                                                                // if W is specified, return the result from the first line
                                                                                W && U ||
                                                                                // otherwise, make a recursive call with the shifted matrix
                                                                                rp(V, 1, V)





                                                                                share|improve this answer











                                                                                $endgroup$















                                                                                  1












                                                                                  1








                                                                                  1





                                                                                  $begingroup$


                                                                                  Japt, 28 bytes



                                                                                  mÏ%2©XÔªX
                                                                                  c éV òUÎl
                                                                                  W©UªßV1V


                                                                                  Try it



                                                                                  Port of Arnauld's answer. The biggest challenge was creating a reusable function. In particular, there is a helper function to reverse every other row. The approach that I am taking is to make a recursive call and depending on whether a variable is set.



                                                                                  Transpiled JS:



                                                                                  // U: first input argument (matrix)
                                                                                  // m: map it through a function
                                                                                  U = U.m(function(X, Y, Z)
                                                                                  // if the row index is even, don't alter it
                                                                                  // if the row index is odd, reverse it (w)
                                                                                  return Y % 2 && X.w() );
                                                                                  V = U
                                                                                  // flatten the matrix
                                                                                  .c()
                                                                                  // shift by the amount specified in second argument
                                                                                  .é(V)
                                                                                  // partition back to matrix
                                                                                  .ò(
                                                                                  // the number of columns should be the same as input
                                                                                  U.g().l()
                                                                                  );
                                                                                  // if W is specified, return the result from the first line
                                                                                  W && U ||
                                                                                  // otherwise, make a recursive call with the shifted matrix
                                                                                  rp(V, 1, V)





                                                                                  share|improve this answer











                                                                                  $endgroup$




                                                                                  Japt, 28 bytes



                                                                                  mÏ%2©XÔªX
                                                                                  c éV òUÎl
                                                                                  W©UªßV1V


                                                                                  Try it



                                                                                  Port of Arnauld's answer. The biggest challenge was creating a reusable function. In particular, there is a helper function to reverse every other row. The approach that I am taking is to make a recursive call and depending on whether a variable is set.



                                                                                  Transpiled JS:



                                                                                  // U: first input argument (matrix)
                                                                                  // m: map it through a function
                                                                                  U = U.m(function(X, Y, Z)
                                                                                  // if the row index is even, don't alter it
                                                                                  // if the row index is odd, reverse it (w)
                                                                                  return Y % 2 && X.w() );
                                                                                  V = U
                                                                                  // flatten the matrix
                                                                                  .c()
                                                                                  // shift by the amount specified in second argument
                                                                                  .é(V)
                                                                                  // partition back to matrix
                                                                                  .ò(
                                                                                  // the number of columns should be the same as input
                                                                                  U.g().l()
                                                                                  );
                                                                                  // if W is specified, return the result from the first line
                                                                                  W && U ||
                                                                                  // otherwise, make a recursive call with the shifted matrix
                                                                                  rp(V, 1, V)






                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited 2 days ago

























                                                                                  answered 2 days ago









                                                                                  danadana

                                                                                  2,051167




                                                                                  2,051167





















                                                                                      1












                                                                                      $begingroup$


                                                                                      Python 3, 94 bytes





                                                                                      lambda m,n:g(roll(g(m),n))
                                                                                      g=lambda b:[b[i][::(-1)**i]for i in r_[:len(b)]]
                                                                                      from numpy import*


                                                                                      Try it online!



                                                                                      Used the odd-row-reversal from Jonathan Allan's answer.



                                                                                      lambda m,n:g(roll(g(m),n)) #reverse odd rows, shift elements, then reverse odd rows again.
                                                                                      g=lambda b:[b[i][::(-1)**i] #reverse odd rows
                                                                                      for i in r_[:len(b)]] #r_[:x] = range(x)
                                                                                      from numpy import* #roll() and r_[]





                                                                                      share|improve this answer











                                                                                      $endgroup$

















                                                                                        1












                                                                                        $begingroup$


                                                                                        Python 3, 94 bytes





                                                                                        lambda m,n:g(roll(g(m),n))
                                                                                        g=lambda b:[b[i][::(-1)**i]for i in r_[:len(b)]]
                                                                                        from numpy import*


                                                                                        Try it online!



                                                                                        Used the odd-row-reversal from Jonathan Allan's answer.



                                                                                        lambda m,n:g(roll(g(m),n)) #reverse odd rows, shift elements, then reverse odd rows again.
                                                                                        g=lambda b:[b[i][::(-1)**i] #reverse odd rows
                                                                                        for i in r_[:len(b)]] #r_[:x] = range(x)
                                                                                        from numpy import* #roll() and r_[]





                                                                                        share|improve this answer











                                                                                        $endgroup$















                                                                                          1












                                                                                          1








                                                                                          1





                                                                                          $begingroup$


                                                                                          Python 3, 94 bytes





                                                                                          lambda m,n:g(roll(g(m),n))
                                                                                          g=lambda b:[b[i][::(-1)**i]for i in r_[:len(b)]]
                                                                                          from numpy import*


                                                                                          Try it online!



                                                                                          Used the odd-row-reversal from Jonathan Allan's answer.



                                                                                          lambda m,n:g(roll(g(m),n)) #reverse odd rows, shift elements, then reverse odd rows again.
                                                                                          g=lambda b:[b[i][::(-1)**i] #reverse odd rows
                                                                                          for i in r_[:len(b)]] #r_[:x] = range(x)
                                                                                          from numpy import* #roll() and r_[]





                                                                                          share|improve this answer











                                                                                          $endgroup$




                                                                                          Python 3, 94 bytes





                                                                                          lambda m,n:g(roll(g(m),n))
                                                                                          g=lambda b:[b[i][::(-1)**i]for i in r_[:len(b)]]
                                                                                          from numpy import*


                                                                                          Try it online!



                                                                                          Used the odd-row-reversal from Jonathan Allan's answer.



                                                                                          lambda m,n:g(roll(g(m),n)) #reverse odd rows, shift elements, then reverse odd rows again.
                                                                                          g=lambda b:[b[i][::(-1)**i] #reverse odd rows
                                                                                          for i in r_[:len(b)]] #r_[:x] = range(x)
                                                                                          from numpy import* #roll() and r_[]






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited 2 days ago

























                                                                                          answered 2 days ago









                                                                                          attinatattinat

                                                                                          58917




                                                                                          58917





















                                                                                              1












                                                                                              $begingroup$


                                                                                              APL (Dyalog Classic), 20 bytes





                                                                                              ↑∘t⊢∘⍴⍴⌽∘∊∘(t←⊢∘⌽↓)


                                                                                              Try it online!






                                                                                              share|improve this answer









                                                                                              $endgroup$

















                                                                                                1












                                                                                                $begingroup$


                                                                                                APL (Dyalog Classic), 20 bytes





                                                                                                ↑∘t⊢∘⍴⍴⌽∘∊∘(t←⊢∘⌽↓)


                                                                                                Try it online!






                                                                                                share|improve this answer









                                                                                                $endgroup$















                                                                                                  1












                                                                                                  1








                                                                                                  1





                                                                                                  $begingroup$


                                                                                                  APL (Dyalog Classic), 20 bytes





                                                                                                  ↑∘t⊢∘⍴⍴⌽∘∊∘(t←⊢∘⌽↓)


                                                                                                  Try it online!






                                                                                                  share|improve this answer









                                                                                                  $endgroup$




                                                                                                  APL (Dyalog Classic), 20 bytes





                                                                                                  ↑∘t⊢∘⍴⍴⌽∘∊∘(t←⊢∘⌽↓)


                                                                                                  Try it online!







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered yesterday









                                                                                                  ngnngn

                                                                                                  7,46612660




                                                                                                  7,46612660





















                                                                                                      1












                                                                                                      $begingroup$


                                                                                                      C# (Visual C# Interactive Compiler), 141 bytes





                                                                                                      a=>n=>for(dynamic l=a.Length,w=a.GetLength(1),i=l,j,b=a.Clone();i-->0;)a[(j=(i+n%l+l)%l)/w,j/w%2<1?j%w:w-j%w-1]=b[i/w,i/w%2<1?i%w:w-i%w-1];


                                                                                                      Try it online!



                                                                                                      -5 bytes total thanks to @someone!



                                                                                                      Anonymous function that performs an in-place modification to the input matrix.



                                                                                                      An single loop iterates over the cells. You can scan from top to bottom and left to right using the following formulas:



                                                                                                      • row=i/w

                                                                                                      • col=i%w

                                                                                                      Where i is a loop counter and w is the number of columns. This is varies slightly when scanning in a snake pattern.



                                                                                                      • row=i/w


                                                                                                      • col=i%w (0th, 2nd, 4th, etc. row)


                                                                                                      • col=w-i%w-1 (1st, 3nd, 5th, etc. row)

                                                                                                      Another thing to note is that the % in C# does not convert to a positive value like it does in some other languages. A couple extra bytes are needed to account for this.



                                                                                                      // a: input matrix
                                                                                                      // n: number of cells to rotate
                                                                                                      a=>n=>
                                                                                                      for(
                                                                                                      // l: total number of cells
                                                                                                      // w: number of columns
                                                                                                      // i: loop index
                                                                                                      // j: offset index
                                                                                                      // b: copy of input matrix
                                                                                                      dynamic
                                                                                                      l=a.Length,
                                                                                                      w=a.GetLength(1),
                                                                                                      i=l,j,
                                                                                                      b=a.Clone();
                                                                                                      // iterate from i down to 0
                                                                                                      i-->0;
                                                                                                      )
                                                                                                      // calculate the offset `j` and use
                                                                                                      // the above formulas to index
                                                                                                      // into `a` for setting a value
                                                                                                      a[
                                                                                                      (j=(i+n%l+l)%l)/w,
                                                                                                      j/w%2<1?j%w:w-j%w-1
                                                                                                      ]=
                                                                                                      // use the un-offset index `i` and
                                                                                                      // the above formulas to read a
                                                                                                      // value from the input matrix
                                                                                                      b[
                                                                                                      i/w,
                                                                                                      i/w%2<1?i%w:w-i%w-1
                                                                                                      ];






                                                                                                      share|improve this answer











                                                                                                      $endgroup$












                                                                                                      • $begingroup$
                                                                                                        You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        23 hours ago










                                                                                                      • $begingroup$
                                                                                                        Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        20 hours ago










                                                                                                      • $begingroup$
                                                                                                        Get rid of y entirely to save 2 bytes: Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        16 hours ago










                                                                                                      • $begingroup$
                                                                                                        @someone - thanks!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        3 hours ago















                                                                                                      1












                                                                                                      $begingroup$


                                                                                                      C# (Visual C# Interactive Compiler), 141 bytes





                                                                                                      a=>n=>for(dynamic l=a.Length,w=a.GetLength(1),i=l,j,b=a.Clone();i-->0;)a[(j=(i+n%l+l)%l)/w,j/w%2<1?j%w:w-j%w-1]=b[i/w,i/w%2<1?i%w:w-i%w-1];


                                                                                                      Try it online!



                                                                                                      -5 bytes total thanks to @someone!



                                                                                                      Anonymous function that performs an in-place modification to the input matrix.



                                                                                                      An single loop iterates over the cells. You can scan from top to bottom and left to right using the following formulas:



                                                                                                      • row=i/w

                                                                                                      • col=i%w

                                                                                                      Where i is a loop counter and w is the number of columns. This is varies slightly when scanning in a snake pattern.



                                                                                                      • row=i/w


                                                                                                      • col=i%w (0th, 2nd, 4th, etc. row)


                                                                                                      • col=w-i%w-1 (1st, 3nd, 5th, etc. row)

                                                                                                      Another thing to note is that the % in C# does not convert to a positive value like it does in some other languages. A couple extra bytes are needed to account for this.



                                                                                                      // a: input matrix
                                                                                                      // n: number of cells to rotate
                                                                                                      a=>n=>
                                                                                                      for(
                                                                                                      // l: total number of cells
                                                                                                      // w: number of columns
                                                                                                      // i: loop index
                                                                                                      // j: offset index
                                                                                                      // b: copy of input matrix
                                                                                                      dynamic
                                                                                                      l=a.Length,
                                                                                                      w=a.GetLength(1),
                                                                                                      i=l,j,
                                                                                                      b=a.Clone();
                                                                                                      // iterate from i down to 0
                                                                                                      i-->0;
                                                                                                      )
                                                                                                      // calculate the offset `j` and use
                                                                                                      // the above formulas to index
                                                                                                      // into `a` for setting a value
                                                                                                      a[
                                                                                                      (j=(i+n%l+l)%l)/w,
                                                                                                      j/w%2<1?j%w:w-j%w-1
                                                                                                      ]=
                                                                                                      // use the un-offset index `i` and
                                                                                                      // the above formulas to read a
                                                                                                      // value from the input matrix
                                                                                                      b[
                                                                                                      i/w,
                                                                                                      i/w%2<1?i%w:w-i%w-1
                                                                                                      ];






                                                                                                      share|improve this answer











                                                                                                      $endgroup$












                                                                                                      • $begingroup$
                                                                                                        You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        23 hours ago










                                                                                                      • $begingroup$
                                                                                                        Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        20 hours ago










                                                                                                      • $begingroup$
                                                                                                        Get rid of y entirely to save 2 bytes: Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        16 hours ago










                                                                                                      • $begingroup$
                                                                                                        @someone - thanks!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        3 hours ago













                                                                                                      1












                                                                                                      1








                                                                                                      1





                                                                                                      $begingroup$


                                                                                                      C# (Visual C# Interactive Compiler), 141 bytes





                                                                                                      a=>n=>for(dynamic l=a.Length,w=a.GetLength(1),i=l,j,b=a.Clone();i-->0;)a[(j=(i+n%l+l)%l)/w,j/w%2<1?j%w:w-j%w-1]=b[i/w,i/w%2<1?i%w:w-i%w-1];


                                                                                                      Try it online!



                                                                                                      -5 bytes total thanks to @someone!



                                                                                                      Anonymous function that performs an in-place modification to the input matrix.



                                                                                                      An single loop iterates over the cells. You can scan from top to bottom and left to right using the following formulas:



                                                                                                      • row=i/w

                                                                                                      • col=i%w

                                                                                                      Where i is a loop counter and w is the number of columns. This is varies slightly when scanning in a snake pattern.



                                                                                                      • row=i/w


                                                                                                      • col=i%w (0th, 2nd, 4th, etc. row)


                                                                                                      • col=w-i%w-1 (1st, 3nd, 5th, etc. row)

                                                                                                      Another thing to note is that the % in C# does not convert to a positive value like it does in some other languages. A couple extra bytes are needed to account for this.



                                                                                                      // a: input matrix
                                                                                                      // n: number of cells to rotate
                                                                                                      a=>n=>
                                                                                                      for(
                                                                                                      // l: total number of cells
                                                                                                      // w: number of columns
                                                                                                      // i: loop index
                                                                                                      // j: offset index
                                                                                                      // b: copy of input matrix
                                                                                                      dynamic
                                                                                                      l=a.Length,
                                                                                                      w=a.GetLength(1),
                                                                                                      i=l,j,
                                                                                                      b=a.Clone();
                                                                                                      // iterate from i down to 0
                                                                                                      i-->0;
                                                                                                      )
                                                                                                      // calculate the offset `j` and use
                                                                                                      // the above formulas to index
                                                                                                      // into `a` for setting a value
                                                                                                      a[
                                                                                                      (j=(i+n%l+l)%l)/w,
                                                                                                      j/w%2<1?j%w:w-j%w-1
                                                                                                      ]=
                                                                                                      // use the un-offset index `i` and
                                                                                                      // the above formulas to read a
                                                                                                      // value from the input matrix
                                                                                                      b[
                                                                                                      i/w,
                                                                                                      i/w%2<1?i%w:w-i%w-1
                                                                                                      ];






                                                                                                      share|improve this answer











                                                                                                      $endgroup$




                                                                                                      C# (Visual C# Interactive Compiler), 141 bytes





                                                                                                      a=>n=>for(dynamic l=a.Length,w=a.GetLength(1),i=l,j,b=a.Clone();i-->0;)a[(j=(i+n%l+l)%l)/w,j/w%2<1?j%w:w-j%w-1]=b[i/w,i/w%2<1?i%w:w-i%w-1];


                                                                                                      Try it online!



                                                                                                      -5 bytes total thanks to @someone!



                                                                                                      Anonymous function that performs an in-place modification to the input matrix.



                                                                                                      An single loop iterates over the cells. You can scan from top to bottom and left to right using the following formulas:



                                                                                                      • row=i/w

                                                                                                      • col=i%w

                                                                                                      Where i is a loop counter and w is the number of columns. This is varies slightly when scanning in a snake pattern.



                                                                                                      • row=i/w


                                                                                                      • col=i%w (0th, 2nd, 4th, etc. row)


                                                                                                      • col=w-i%w-1 (1st, 3nd, 5th, etc. row)

                                                                                                      Another thing to note is that the % in C# does not convert to a positive value like it does in some other languages. A couple extra bytes are needed to account for this.



                                                                                                      // a: input matrix
                                                                                                      // n: number of cells to rotate
                                                                                                      a=>n=>
                                                                                                      for(
                                                                                                      // l: total number of cells
                                                                                                      // w: number of columns
                                                                                                      // i: loop index
                                                                                                      // j: offset index
                                                                                                      // b: copy of input matrix
                                                                                                      dynamic
                                                                                                      l=a.Length,
                                                                                                      w=a.GetLength(1),
                                                                                                      i=l,j,
                                                                                                      b=a.Clone();
                                                                                                      // iterate from i down to 0
                                                                                                      i-->0;
                                                                                                      )
                                                                                                      // calculate the offset `j` and use
                                                                                                      // the above formulas to index
                                                                                                      // into `a` for setting a value
                                                                                                      a[
                                                                                                      (j=(i+n%l+l)%l)/w,
                                                                                                      j/w%2<1?j%w:w-j%w-1
                                                                                                      ]=
                                                                                                      // use the un-offset index `i` and
                                                                                                      // the above formulas to read a
                                                                                                      // value from the input matrix
                                                                                                      b[
                                                                                                      i/w,
                                                                                                      i/w%2<1?i%w:w-i%w-1
                                                                                                      ];







                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited 3 hours ago

























                                                                                                      answered Apr 14 at 21:55









                                                                                                      danadana

                                                                                                      2,051167




                                                                                                      2,051167











                                                                                                      • $begingroup$
                                                                                                        You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        23 hours ago










                                                                                                      • $begingroup$
                                                                                                        Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        20 hours ago










                                                                                                      • $begingroup$
                                                                                                        Get rid of y entirely to save 2 bytes: Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        16 hours ago










                                                                                                      • $begingroup$
                                                                                                        @someone - thanks!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        3 hours ago
















                                                                                                      • $begingroup$
                                                                                                        You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        23 hours ago










                                                                                                      • $begingroup$
                                                                                                        Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        20 hours ago










                                                                                                      • $begingroup$
                                                                                                        Get rid of y entirely to save 2 bytes: Try it online!
                                                                                                        $endgroup$
                                                                                                        – someone
                                                                                                        16 hours ago










                                                                                                      • $begingroup$
                                                                                                        @someone - thanks!
                                                                                                        $endgroup$
                                                                                                        – dana
                                                                                                        3 hours ago















                                                                                                      $begingroup$
                                                                                                      You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                                                                                                      $endgroup$
                                                                                                      – someone
                                                                                                      23 hours ago




                                                                                                      $begingroup$
                                                                                                      You can save 3 bytes by merging declarations with dynamic; comment too l. Try it online!
                                                                                                      $endgroup$
                                                                                                      – someone
                                                                                                      23 hours ago












                                                                                                      $begingroup$
                                                                                                      Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                                                                                                      $endgroup$
                                                                                                      – dana
                                                                                                      20 hours ago




                                                                                                      $begingroup$
                                                                                                      Nice :) That declaration can be moved into the loop as well. I tend to use var for golfing which doesn't let you declare a list of variables. Probably why I missed this. Good catch!
                                                                                                      $endgroup$
                                                                                                      – dana
                                                                                                      20 hours ago












                                                                                                      $begingroup$
                                                                                                      Get rid of y entirely to save 2 bytes: Try it online!
                                                                                                      $endgroup$
                                                                                                      – someone
                                                                                                      16 hours ago




                                                                                                      $begingroup$
                                                                                                      Get rid of y entirely to save 2 bytes: Try it online!
                                                                                                      $endgroup$
                                                                                                      – someone
                                                                                                      16 hours ago












                                                                                                      $begingroup$
                                                                                                      @someone - thanks!
                                                                                                      $endgroup$
                                                                                                      – dana
                                                                                                      3 hours ago




                                                                                                      $begingroup$
                                                                                                      @someone - thanks!
                                                                                                      $endgroup$
                                                                                                      – dana
                                                                                                      3 hours ago

















                                                                                                      draft saved

                                                                                                      draft discarded
















































                                                                                                      If this is an answer to a challenge…



                                                                                                      • …Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.


                                                                                                      • …Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
                                                                                                        Explanations of your answer make it more interesting to read and are very much encouraged.


                                                                                                      • …Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.


                                                                                                      More generally…



                                                                                                      • …Please make sure to answer the question and provide sufficient detail.


                                                                                                      • …Avoid asking for help, clarification or responding to other answers (use comments instead).




                                                                                                      draft saved


                                                                                                      draft discarded














                                                                                                      StackExchange.ready(
                                                                                                      function ()
                                                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f183153%2fslither-like-a-snake%23new-answer', 'question_page');

                                                                                                      );

                                                                                                      Post as a guest















                                                                                                      Required, but never shown





















































                                                                                                      Required, but never shown














                                                                                                      Required, but never shown












                                                                                                      Required, but never shown







                                                                                                      Required, but never shown

































                                                                                                      Required, but never shown














                                                                                                      Required, but never shown












                                                                                                      Required, but never shown







                                                                                                      Required, but never shown







                                                                                                      Popular posts from this blog

                                                                                                      Sum ergo cogito? 1 nng

                                                                                                      419 nièngy_Soadمي 19bal1.5o_g

                                                                                                      Queiggey Chernihivv 9NnOo i Zw X QqKk LpB