- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flip the matrix horizontally and invert it using JavaScript
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 −
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 ] ]
- Related Articles
- Flip and Invert Matrix in Python
- How to flip an Ellipse horizontally using FabricJS?
- How to flip a Circle horizontally using FabricJS?
- How to flip a Triangle horizontally using FabricJS?
- How to flip a Rectangle horizontally using FabricJS?
- How to flip a Textbox horizontally using FabricJS?
- Random Flip Matrix in C++
- How to invert a matrix or nArray in Python?
- How to invert an object in JavaScript?
- How to Invert the color of an image using JavaFX?
- How can it be possible to invert a string in MySQL?
- How to join two images horizontally and vertically using OpenCV Python?
- How to print the contents of array horizontally using C#?
- How to invert a binary image in OpenCV using C++?
- How to flip an Ellipse vertically using FabricJS?

Advertisements