Open In App

JavaScript Program to Interchange Elements of First & Last in a Matrix Across Columns

We are given a matrix and we have to interchange the elements of the first and last columns with each other in a matrix.

Example:

Input 1 : 
1 1 5 0
2 3 7 2
8 9 1 3
6 7 8 2

Output 1 :
0 1 5 1
2 3 7 2
3 9 1 8
2 7 8 6

Using the swapping logic

In this method, we Iterate through each column of the matrix and swap elements of the first and last column using a temporary variable to interchange them.

Example: The below code implements swapping logic to interchange elements of first and last column in a matrix.

function swapFirstLast(mat) {
    const rows = mat.length;
    for (let i = 0; i < rows; i++) {
        const cols = mat[i].length;
        let temp = mat[i][0];
        mat[i][0] = mat[i][cols - 1];
        mat[i][cols - 1] = temp;
    }
}

function main() {
    let mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ];
    console.log("Input Matrix:");
    for (let row of mat) {
        console.log(row.join(" "));
    }
    swapFirstLast(mat);
    console.log("Swapped Matrix:");
    for (let row of mat) {
        console.log(row.join(" "));
    }
}
main();

Output
Input Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Swapped Matrix:
4 2 3 1
8 6 7 5
12 10 11 9

Time Complexity: O(N*M),where n is the number of rows and m is the number of columns.

Auxiliary Space: O(1)

Using forEach method

In this method, we use the forEach method to iterate through each row of the matrix and swap elements of the first and last columns in each row.

Example: The below code example implements the forEach method to interchange elements of first and last row in a matrix using array destructuring assignment.

function swapFirstLastWithMap(mat) {
    mat.forEach(row =>
        [row[0], row[row.length - 1]] =
        [row[row.length - 1], row[0]]);
}

function main() {
    let mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ];
    console.log("Input Matrix:");
    for (let row of mat) {
        console.log(row.join(" "));
    }
    swapFirstLastWithMap(mat);
    console.log("Swapped Matrix:");
    for (let row of mat) {
        console.log(row.join(" "));
    }
}
main();

Output
Input Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Swapped Matrix:
4 2 3 1
8 6 7 5
12 10 11 9

Time Complexity: O(N *M),where n is the number of rows and m is the number of columns.

Auxiliary Space: O(1)

Article Tags :