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?
What is a Meta algorithm?
Is there a way in Ruby to make just any one out of many keyword arguments required?
3 doors, three guards, one stone
Antler Helmet: Can it work?
What LEGO pieces have "real-world" functionality?
Why did the IBM 650 use bi-quinary?
Do you forfeit tax refunds/credits if you aren't required to and don't file by April 15?
How discoverable are IPv6 addresses and AAAA names by potential attackers?
Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?
How do I mention the quality of my school without bragging
Why is "Captain Marvel" translated as male in Portugal?
Stars Make Stars
Is there a Spanish version of "dot your i's and cross your t's" that includes the letter 'ñ'?
What makes black pepper strong or mild?
Why is black pepper both grey and black?
When to stop saving and start investing?
How widely used is the term Treppenwitz? Is it something that most Germans know?
What are 'alternative tunings' of a guitar and why would you use them? Doesn't it make it more difficult to play?
Is above average number of years spent on PhD considered a red flag in future academia or industry positions?
Output the ŋarâþ crîþ alphabet song without using (m)any letters
Is the Standard Deduction better than Itemized when both are the same amount?
Bonus calculation: Am I making a mountain out of a molehill?
Right-skewed distribution with mean equals to mode?
Can inflation occur in a positive-sum game currency system such as the Stack Exchange reputation system?
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?
$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
code-golf array-manipulation matrix
$endgroup$
add a comment |
$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
code-golf array-manipulation matrix
$endgroup$
4
$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
yesterday
4
$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
yesterday
add a comment |
$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
code-golf array-manipulation matrix
$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
code-golf array-manipulation matrix
edited yesterday
Jonah
asked yesterday
JonahJonah
2,7811018
2,7811018
4
$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
yesterday
4
$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
yesterday
add a comment |
4
$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
yesterday
4
$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
yesterday
4
4
$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
yesterday
$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
yesterday
4
4
$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
yesterday
$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
yesterday
add a comment |
11 Answers
11
active
oldest
votes
$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
$endgroup$
add a comment |
$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
$endgroup$
add a comment |
$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.
$endgroup$
add a comment |
$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
$endgroup$
add a comment |
$begingroup$
J, 41 30 21 bytes
-11 bytes thanks to Jonah!
-9 bytes thanks to FrownyFrog!
$@]t@$(|.,@t=.|.@]/)
Try it online!
Reversed +/-
$endgroup$
1
$begingroup$
30 bytes, +/- not reversed, but still uses helper:$@]t@$(|.,@(t=.#,`(|.@,)/.]))(Try it online!)
$endgroup$
– Jonah
21 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours 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
17 hours ago
1
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
|
show 1 more comment
$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.)
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 bytes
a=>n=>int l=a.Length,w=a.GetLength(1),i=l,j,y;for(dynamic b=a.Clone();i-->0;)a[y=(j=(i+n%l+l)%l)/w,y%2<1?j%w:w-j%w-1]=b[y=i/w,y%2<1?i%w:w-i%w-1];
Try it online!
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/wcol=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/wcol=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=>
// l: total number of cells
// w: number of columns
// i: loop index
// j: offset index
// y: current row
int
l=a.Length,
w=a.GetLength(1),
i=l,j,y;
// copy of the initial matrix to b
// and iterate from `l` down to `0`
for(dynamic b=a.Clone();i-->0;)
// calculate the offset `j` and use
// the above formulas to index
// into `a` for setting a value
a[
y=(j=(i+n%l+l)%l)/w,
y%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[
y=i/w,
y%2<1?i%w:w-i%w-1
];
$endgroup$
add a comment |
$begingroup$
Pyth, 20 bytes
L.e_W%k2bbyclQ.>syQE
Try it online here.
$endgroup$
add a comment |
$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!
$endgroup$
add a comment |
$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) );
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)
$endgroup$
add a comment |
$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. :(
$endgroup$
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
$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
$endgroup$
add a comment |
$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
$endgroup$
add a comment |
$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
$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
edited yesterday
answered yesterday
Jonathan AllanJonathan Allan
54.4k537174
54.4k537174
add a comment |
add a comment |
$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
$endgroup$
add a comment |
$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
$endgroup$
add a comment |
$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
$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
edited yesterday
answered yesterday
Kirill L.Kirill L.
6,2181528
6,2181528
add a comment |
add a comment |
$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.
$endgroup$
add a comment |
$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.
$endgroup$
add a comment |
$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.
$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.
edited yesterday
answered yesterday
Jonathan AllanJonathan Allan
54.4k537174
54.4k537174
add a comment |
add a comment |
$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
$endgroup$
add a comment |
$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
$endgroup$
add a comment |
$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
$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
edited yesterday
answered yesterday
ArnauldArnauld
81.1k797334
81.1k797334
add a comment |
add a comment |
$begingroup$
J, 41 30 21 bytes
-11 bytes thanks to Jonah!
-9 bytes thanks to FrownyFrog!
$@]t@$(|.,@t=.|.@]/)
Try it online!
Reversed +/-
$endgroup$
1
$begingroup$
30 bytes, +/- not reversed, but still uses helper:$@]t@$(|.,@(t=.#,`(|.@,)/.]))(Try it online!)
$endgroup$
– Jonah
21 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours 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
17 hours ago
1
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
|
show 1 more comment
$begingroup$
J, 41 30 21 bytes
-11 bytes thanks to Jonah!
-9 bytes thanks to FrownyFrog!
$@]t@$(|.,@t=.|.@]/)
Try it online!
Reversed +/-
$endgroup$
1
$begingroup$
30 bytes, +/- not reversed, but still uses helper:$@]t@$(|.,@(t=.#,`(|.@,)/.]))(Try it online!)
$endgroup$
– Jonah
21 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours 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
17 hours ago
1
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
|
show 1 more comment
$begingroup$
J, 41 30 21 bytes
-11 bytes thanks to Jonah!
-9 bytes thanks to FrownyFrog!
$@]t@$(|.,@t=.|.@]/)
Try it online!
Reversed +/-
$endgroup$
J, 41 30 21 bytes
-11 bytes thanks to Jonah!
-9 bytes thanks to FrownyFrog!
$@]t@$(|.,@t=.|.@]/)
Try it online!
Reversed +/-
edited 11 hours ago
answered yesterday
Galen IvanovGalen Ivanov
7,47211034
7,47211034
1
$begingroup$
30 bytes, +/- not reversed, but still uses helper:$@]t@$(|.,@(t=.#,`(|.@,)/.]))(Try it online!)
$endgroup$
– Jonah
21 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours 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
17 hours ago
1
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
|
show 1 more comment
1
$begingroup$
30 bytes, +/- not reversed, but still uses helper:$@]t@$(|.,@(t=.#,`(|.@,)/.]))(Try it online!)
$endgroup$
– Jonah
21 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours 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
17 hours ago
1
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
1
1
$begingroup$
30 bytes, +/- not reversed, but still uses helper:
$@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)$endgroup$
– Jonah
21 hours ago
$begingroup$
30 bytes, +/- not reversed, but still uses helper:
$@]t@$(|.,@(t=.#,`(|.@,)/.])) (Try it online!)$endgroup$
– Jonah
21 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours ago
$begingroup$
correction: +/- still reversed.
$endgroup$
– Jonah
19 hours 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
17 hours 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
17 hours ago
1
1
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
21 bytes, thx @ngn
$endgroup$
– FrownyFrog
12 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
$begingroup$
@FrownyFrog Wow, it's half the initial size now. I feel stupid... Thanks!
$endgroup$
– Galen Ivanov
11 hours ago
|
show 1 more comment
$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.)
$endgroup$
add a comment |
$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.)
$endgroup$
add a comment |
$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.)
$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.)
answered yesterday
NeilNeil
82.8k745179
82.8k745179
add a comment |
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 bytes
a=>n=>int l=a.Length,w=a.GetLength(1),i=l,j,y;for(dynamic b=a.Clone();i-->0;)a[y=(j=(i+n%l+l)%l)/w,y%2<1?j%w:w-j%w-1]=b[y=i/w,y%2<1?i%w:w-i%w-1];
Try it online!
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/wcol=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/wcol=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=>
// l: total number of cells
// w: number of columns
// i: loop index
// j: offset index
// y: current row
int
l=a.Length,
w=a.GetLength(1),
i=l,j,y;
// copy of the initial matrix to b
// and iterate from `l` down to `0`
for(dynamic b=a.Clone();i-->0;)
// calculate the offset `j` and use
// the above formulas to index
// into `a` for setting a value
a[
y=(j=(i+n%l+l)%l)/w,
y%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[
y=i/w,
y%2<1?i%w:w-i%w-1
];
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 bytes
a=>n=>int l=a.Length,w=a.GetLength(1),i=l,j,y;for(dynamic b=a.Clone();i-->0;)a[y=(j=(i+n%l+l)%l)/w,y%2<1?j%w:w-j%w-1]=b[y=i/w,y%2<1?i%w:w-i%w-1];
Try it online!
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/wcol=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/wcol=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=>
// l: total number of cells
// w: number of columns
// i: loop index
// j: offset index
// y: current row
int
l=a.Length,
w=a.GetLength(1),
i=l,j,y;
// copy of the initial matrix to b
// and iterate from `l` down to `0`
for(dynamic b=a.Clone();i-->0;)
// calculate the offset `j` and use
// the above formulas to index
// into `a` for setting a value
a[
y=(j=(i+n%l+l)%l)/w,
y%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[
y=i/w,
y%2<1?i%w:w-i%w-1
];
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 bytes
a=>n=>int l=a.Length,w=a.GetLength(1),i=l,j,y;for(dynamic b=a.Clone();i-->0;)a[y=(j=(i+n%l+l)%l)/w,y%2<1?j%w:w-j%w-1]=b[y=i/w,y%2<1?i%w:w-i%w-1];
Try it online!
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/wcol=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/wcol=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=>
// l: total number of cells
// w: number of columns
// i: loop index
// j: offset index
// y: current row
int
l=a.Length,
w=a.GetLength(1),
i=l,j,y;
// copy of the initial matrix to b
// and iterate from `l` down to `0`
for(dynamic b=a.Clone();i-->0;)
// calculate the offset `j` and use
// the above formulas to index
// into `a` for setting a value
a[
y=(j=(i+n%l+l)%l)/w,
y%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[
y=i/w,
y%2<1?i%w:w-i%w-1
];
$endgroup$
C# (Visual C# Interactive Compiler), 147 bytes
a=>n=>int l=a.Length,w=a.GetLength(1),i=l,j,y;for(dynamic b=a.Clone();i-->0;)a[y=(j=(i+n%l+l)%l)/w,y%2<1?j%w:w-j%w-1]=b[y=i/w,y%2<1?i%w:w-i%w-1];
Try it online!
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/wcol=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/wcol=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=>
// l: total number of cells
// w: number of columns
// i: loop index
// j: offset index
// y: current row
int
l=a.Length,
w=a.GetLength(1),
i=l,j,y;
// copy of the initial matrix to b
// and iterate from `l` down to `0`
for(dynamic b=a.Clone();i-->0;)
// calculate the offset `j` and use
// the above formulas to index
// into `a` for setting a value
a[
y=(j=(i+n%l+l)%l)/w,
y%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[
y=i/w,
y%2<1?i%w:w-i%w-1
];
edited 19 hours ago
answered yesterday
danadana
1,981167
1,981167
add a comment |
add a comment |
$begingroup$
Pyth, 20 bytes
L.e_W%k2bbyclQ.>syQE
Try it online here.
$endgroup$
add a comment |
$begingroup$
Pyth, 20 bytes
L.e_W%k2bbyclQ.>syQE
Try it online here.
$endgroup$
add a comment |
$begingroup$
Pyth, 20 bytes
L.e_W%k2bbyclQ.>syQE
Try it online here.
$endgroup$
Pyth, 20 bytes
L.e_W%k2bbyclQ.>syQE
Try it online here.
answered 13 hours ago
SokSok
4,197925
4,197925
add a comment |
add a comment |
$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!
$endgroup$
add a comment |
$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!
$endgroup$
add a comment |
$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!
$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!
answered 13 hours ago
attinatattinat
5597
5597
add a comment |
add a comment |
$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) );
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)
$endgroup$
add a comment |
$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) );
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)
$endgroup$
add a comment |
$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) );
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)
$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) );
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)
edited 7 hours ago
answered 13 hours ago
danadana
1,981167
1,981167
add a comment |
add a comment |
$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. :(
$endgroup$
add a comment |
$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. :(
$endgroup$
add a comment |
$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. :(
$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. :(
answered 2 hours ago
Erik the OutgolferErik the Outgolfer
33.1k429106
33.1k429106
add a comment |
add a comment |
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).
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
4
$begingroup$
Reversing meaning of +/- is fine. I think the entrance should stay at the top left though.
$endgroup$
– Jonah
yesterday
4
$begingroup$
This definitely needs an answer in Python.
$endgroup$
– gwaugh
yesterday