Solving the Flip and Invert Matrix Algorithm
I’ve worked with matrix algorithms before, so I’m always curious about finding new ways to solve them. Here’s one I did recently:
You are given a two-dimensional integer matrix
matrix
containing1
s and0
s. For each row inmatrix
, reverse the row. Then, flip each value in the matrix such that any1
becomes0
and any0
becomes1
.
An example input:
matrix = [
[1, 1, 0],
[0, 0, 1],
[0, 0, 0]
]
Expected output:
[
[1, 0, 0],
[0, 1, 1],
[1, 1, 1]
]
Step 1)
Before anything, it’s always good to add a condition that checks if the matrix is empty. You can use something like below:
const flipReverse = matrix => { if(matrix.length === 0) return []}
Step 2)
As the instructions indicate, we need to reverse each row in the matrix. So, I create a new variable called reversedMatrix
, which will hold the new array of arrays with reversed values. Then, I map over the original matrix
array and reverse each subarray.
const flipReverse = matrix => { if(matrix.length === 0) return [] let reversedMatrix = matrix.map(subArr => subArr.reverse()) return reversedMatrix}// [
[0, 1, 1],
[1, 0, 0],
[0, 0, 0]
]
As you can see, it returns the desired result. Now, each row is reversed.
Step 3)
Next, we need to flip each value from 0 to 1 OR from 1 to 0. Since we’re working with an array of arrays, we will need to use a nested for
loop.
In our outer loop, we will set the condition so that the loop runs from the first index (first subarray) 0 until the end (the length of the array). In our inner loop, we create a variable j
to keep track of which element we’re iterating over within each subarray. We specify the condition j < reversedMatrix[i].length
to indicate that we’re looking at each element within each subarray of the larger array i
.
Then, we create conditions to check the value of each element within the subarray. If it’s equal to 0, we’ll change it to 1. Our else
statement handles if it’s equal to 1. Once we exit out of the loops, we return our final reversedMatrix.
And our solution in console looks like: