Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions 1260.shift-2d-grid.js
Original file line number Diff line number Diff line change
@@ -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;
9 changes: 9 additions & 0 deletions shiftGrid.test.js
Original file line number Diff line number Diff line change
@@ -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]]);
});