diff --git a/1260.shift-2d-grid.js b/1260.shift-2d-grid.js new file mode 100644 index 00000000..565de0ca --- /dev/null +++ b/1260.shift-2d-grid.js @@ -0,0 +1,29 @@ +/* URL of this problem + * https://leetcode.com/problems/shift-2d-grid/description/ + * + * @param {number[][]} grid + * @param {number} k + * @return {number[][]} + */ + +var shiftGrid = function(grid, k) { + const Row = grid.length; + const Column = grid[0].length; + const FlatGrid = grid.flat(); + const ShiftedGrid = []; + + // Execute the shift operations + for (let i = 0; i < k; i++) { + FlatGrid.unshift(FlatGrid.pop()); + } + // Create a 2D array after all the shift operations + for (let i = 0; i < Row; i++) { + const CurrRow = FlatGrid.splice(0, Column); + + ShiftedGrid.push(CurrRow); + } + + return ShiftedGrid; +}; + +module.exports = shiftGrid; \ No newline at end of file diff --git a/shiftGrid.test.js b/shiftGrid.test.js new file mode 100644 index 00000000..709e831f --- /dev/null +++ b/shiftGrid.test.js @@ -0,0 +1,9 @@ +const shiftGrid = require("../jest-test/1260.shift-2d-grid"); + +test("Return the array after the shift operations", () => { + expect(shiftGrid([[1,2,3],[4,5,6],[7,8,9]], 1)).toEqual([[9,1,2],[3,4,5],[6,7,8]]); +}); + +test("Return the original 2D array if the argument k is 0", () => { + expect(shiftGrid([[1,2,3],[4,5,6],[7,8,9]], 0)).toEqual([[1,2,3],[4,5,6],[7,8,9]]); +}); \ No newline at end of file