Mastering Matrices in Javascript: A guide to Multidimensional Arrays (Part 1)
When first solving problems with multidimensional arrays it can be a little intimidating. In this article we will examine some easy problems to understand some patterns, and move along to more difficult ones. You can follow-along and test your understanding by completing the leetcode problems mentioned. Good luck!
The first problem we will be looking at is Leetcode 1572. In this problem you are given a Matrix and asked to find the sum of the two diagonal.
Step by Step:
- Set a variable sum=0 to track the sum of the two diagonals
- Set a variable j which will be used to find the D2 in our matrix. The value will be equal to the index of the last item of our rows j= arr[0].length-1 (in this case 3). This will be decremented by our iteration in the next step.
- Now we will iterate through the matrix adding a third variable i=0 which will be used to find both diagonals D1= arr[i][j], and D2=arr[i][i]. In our iteration we will increase i each time, and j will decrease each time.
- We will add the condition if(i !== j) to prevent from counting the center twice (in the case of a (3 by 3 array).
- Now every-time we iterate through we will move both diagonals towards the bottom (left or right) of the array, and add the value to the sum.
- This will stop once i = 4 and is no longer < arr.length
This can also be done with a forEach loop as you can see below.
The next problem we will be looking at is Leetcode 1380. Here we are asked to return the number that is both the minimum in its row and maximum in its column.
Step by Step:
- Iterate though the matrix.
- Set variable min= Infinity so we have a starting point (to compare min to in the next line).
- Then we will equal min to the smallest value for that row (…matrix[i]). In the first iteration the number will be compared to infinity (Math.min(min, )) since it will be smaller it will update the value of min.
- Next we will find the index of the min value, which we will use as the column (minIndex = matrix[i].indexOf(min))
- After finding the min of the row we will use the index (as the column) in our while loop to find the max value in that column, by comparing each number in the column to the previous max value.
- At the end of each while loop iteration we will see if the minimum value of that row is equal to the max value of that column min === max. If so we got our column!