Computer >> Computer tutorials >  >> Programming >> Javascript

Spiraling the elements of a square matrix JavaScript


We are required to write a JavaScript function that takes in two-dimensional (necessarily a square matrix) array of arrays of literals like this −

const arr = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

The function should construct a new array that takes elements spirally from the input array starting from position (0, 0) and return that single dimensional array.

Therefore, for this array, the spiral should look like −

const output = [1, 2, 3, 6, 9, 8, 7, 4, 5];

We will create a temporary variable that point at the current row and current column, both at the start and the end.

That way, we can iteratively increment the starting row and starting column and decrement the ending row and ending column in a manner that spirals toward the center of the matrix.

Example

const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
const spiral = (arr = []) => {
   if (!arr || arr.length === 0) {
      return [];
   };
   let startRow = 0;
   let startCol = 0;
   let res = [];
   let endCol = arr[0].length - 1;
   let endRow = arr.length - 1;
   while (startRow <= endRow && startCol <= endCol) {
      for (let i = startCol; i <= endCol; i++) {
         res.push(arr[startRow][i]);
      }
      startRow++;
      for (let i = startRow; i <= endRow; i++) {
         res.push(arr[i][endCol]);
      }
      endCol--;
      if (startRow <= endRow) {
         for (let i = endCol; i >= startCol; i--) {
            res.push(arr[endRow][i]);
         }
         endRow--;
      }
      if (startCol <= endCol) {
         for (let i = endRow; i >= startRow; i--) {
            res.push(arr[i][startCol]);
         } startCol++;
      }
   }
   return res;
};
console.log(spiral(arr));

Output

And the output in the console will be −

[
   1, 2, 3, 6, 9,
   8, 7, 4, 5
]