DEV Community 👩‍💻👨‍💻

Cover image for Road to Genius: superior #57
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: superior #57

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 - 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 = [[8, 1, 1], [8, 8, 7], [8, 6, 4]];
🐼(M);
let A = M[2][0];

// 💎 = ? (number)
// 💰 = ? (identifier)
// 💚 = ? (identifier)
// 🐼 = ? (identifier)
// such that A = 4 (number)
Enter fullscreen mode Exit fullscreen mode

We've encountered this code before several episodes ago; it's all about rotating a matrix by 90° clockwise. This time we have to fix four bugs to complete the challenge. We can either cheat by looking at the code from several posts ago, or solve it the hard way (which is quicker actually).

The first three bugs appear on the same line:

swap(M, [i, j], [💚 - 💰 - 💎, n - i - 1]);
Enter fullscreen mode Exit fullscreen mode

The first two for-loops are rotating the matrix by 90° but their column-order won't be respected (that's what the last two for-loops are for). The bugs should be the same as its neighboring index:

swap(M, [i, j], [n - i - 1, n - i - 1]);
Enter fullscreen mode Exit fullscreen mode

The final bug 🐼 should be a call to the function rotate.

coding challenge answer

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)

🌚 Life is too short to browse without dark mode