From 763fc0430fd934a4da9109ccf49663ec2a4fa614 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Wed, 11 Jan 2023 09:54:31 -0800 Subject: [PATCH 1/2] solve 1260. Shift 2D Grid --- 1260.shift-2d-grid.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1260.shift-2d-grid.js 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 From c1f63e1de177732cb96413fced2beee9466a7884 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Wed, 11 Jan 2023 09:54:59 -0800 Subject: [PATCH 2/2] test function shiftGrid --- shiftGrid.test.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 shiftGrid.test.js 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