Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.
function swap(arr, [i, j], [m, n]) {
const temp = arr[i][j];
arr[i][j] = arr[m][n];
arr[m][n] = temp;
}
function rotate(M) {
const n = M.length;
for (let i = 0; i < n-1; i++) {
for (let j = 0; j < n-i; j++) {
swap(M, [i, j], [n-j-1, n-i-1]);
}
}
for (let i = 0; i < n/2; i++) {
for (let j = 0; j < n; j++) {
swap(M, [i, j], [n-i-1, j]);
}
}
}
let M = [
[6,5,9],
[8,1,5],
[3,4,1]
]
rotate(M);
let A = M[2][1]
// A = ? (number)
We've encountered this code a couple times before, it's about rotating a matrix by 90 degrees clockwise. By now this should be a piece of cake!
Here's some pseudocode:
M = [
6 5 9
8 1 5
3 4 1
]
rotate 90°
M = [
3 8 6
4 1 5
1 5 9
]
To find the answer we need to find A = M[2][1]
in the rotated matrix, which is 5 (on 3rd row and 2nd column).
By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/
Top comments (0)