Flip the matrix horizontally and invert it using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a 2-D binary array, arr, (an array that consists of only 0 or 1), as the first and the only argument.

Our function should first flip the matrix horizontally, then invert it, and return the resulting matrix.

To flip the matrix horizontally means that each row of the matrix is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].

To invert a matrix means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].

For example, if the input to the function is

Input

const arr = [
   [1, 1, 0],
   [1, 0, 1],
   [0, 0, 0]
];

Output

const output = [
   [1,0,0],
   [0,1,0],
   [1,1,1]
];

Output Explanation

First we reverse each row −

[[0,1,1],[1,0,1],[0,0,0]]

Then, we invert the matrix −

[[1,0,0],[0,1,0],[1,1,1]]

Example

Following is the code −

 Live Demo

const arr = [
   [1, 1, 0],
   [1, 0, 1],
   [0, 0, 0]
];
const flipAndInvert = (arr = []) => {
   const invert = n => (n === 1 ? 0 : 1)
   for(let i = 0; i < arr.length; i++) {
      for(let j = 0; j < arr[i].length / 2; j++) {
         const index2 = arr[i].length - 1 - j
         if(j === index2) {
            arr[i][j] = invert(arr[i][j])
         } else {
            const temp = arr[i][j]
            arr[i][j] = arr[i][index2]
            arr[i][index2] = temp
            arr[i][j] = invert(arr[i][j])
            arr[i][index2] = invert(arr[i][index2])
         }
      }
   }
};
flipAndInvert(arr);
console.log(arr);

Output

[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 1, 1, 1 ] ]
raja
Published on 24-Apr-2021 09:51:16
Advertisements