Reshape Matrix in JavaScript

Easy
3
20.7% Acceptance

In this lab, you will be implementing a function called matrixReshape, which will emulate the behavior of MATLAB's reshape function. This function will take an m x n matrix mat and two integers r and c, representing the new number of rows and columns for the reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix while maintaining the original row-traversing order.

If the reshape operation with the given parameters is possible and legal, the function will return the new reshaped matrix; otherwise, it will return the original matrix.

Example 1:

Consider the following input:

mat = [[1,2],[3,4]], r = 1, c = 4

The reshaped matrix should look like the following:

[[1, 2, 3, 4]]

Example 2:

Consider the following input:

mat = [[1,2],[3,4]], r = 2, c = 4

In this case, the provided r and c values are not legal for reshaping the matrix, so the output should be the original input matrix:

[[1, 2], [3, 4]]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

Your task is to complete the implementation of the matrixReshape function in the given index.js file, as well as to implement the challenges and evaluation script for this lab.

Make sure to follow all the instructions and guidelines mentioned above to ensure the lab's proper functionality.