21
1
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
4Reversing meaning of +/- is fine. I think the entrance should stay at the top left though. – Jonah – 2019-04-14T01:24:55.577
7This definitely needs an answer in Python. – 640KB – 2019-04-14T13:47:46.693