curriculum/challenges/english/blocks/daily-coding-challenges-python/698a1a73ade5ac0e19180fa4.md
Given a matrix (array of arrays) of numbers and an integer, shift all values in the matrix by the given amount.
Values should wrap:
For example, given:
[
[1, 2, 3],
[4, 5, 6]
]
with a shift of 1, move all the numbers to the right one:
[
[6, 1, 2],
[3, 4, 5]
]
shift_matrix([[1, 2, 3], [4, 5, 6]], 1) should return [[6, 1, 2], [3, 4, 5]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(shift_matrix([[1, 2, 3], [4, 5, 6]], 1), [[6, 1, 2], [3, 4, 5]])`)
}})
shift_matrix([[1, 2, 3], [4, 5, 6]], -1) should return [[2, 3, 4], [5, 6, 1]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(shift_matrix([[1, 2, 3], [4, 5, 6]], -1), [[2, 3, 4], [5, 6, 1]])`)
}})
shift_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5) should return [[5, 6, 7], [8, 9, 1], [2, 3, 4]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(shift_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5), [[5, 6, 7], [8, 9, 1], [2, 3, 4]])`)
}})
shift_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], -6) should return [[7, 8, 9], [1, 2, 3], [4, 5, 6]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(shift_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], -6), [[7, 8, 9], [1, 2, 3], [4, 5, 6]])`)
}})
shift_matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 7) should return [[10, 11, 12, 13], [14, 15, 16, 1], [2, 3, 4, 5], [6, 7, 8, 9]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(shift_matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 7), [[10, 11, 12, 13], [14, 15, 16, 1], [2, 3, 4, 5], [6, 7, 8, 9]])`)
}})
shift_matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], -54) should return [[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 1, 2], [3, 4, 5, 6]].
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(shift_matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], -54), [[7, 8, 9, 10], [11, 12, 13, 14], [15, 16, 1, 2], [3, 4, 5, 6]])`)
}})
def shift_matrix(matrix, shift):
return matrix
def shift_matrix(matrix, shift):
rows = len(matrix)
cols = len(matrix[0])
flat = [num for row in matrix for num in row]
n = len(flat)
s = shift % n
shifted = flat[-s:] + flat[:-s] if s != 0 else flat[:]
result = []
for i in range(rows):
result.append(shifted[i*cols:(i+1)*cols])
return result