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.
Our good old friend Gauss Jordan is is back!
function gaussjordan(m, eps) { if (!eps) eps = 1e-10; let h = ๐ผ.length, w = m[0].length, y = -1, y2, x; while (++y < h) { let maxrow = y; y2 = y; while (++y2 < h) { if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y])) maxrow = y2; } let tmp = m[y]; m[y] = m[maxrow]; m[maxrow] = tmp; if (Math.abs(m[y][y]) <= eps) return false; y2 = y; while (++y2 < h) { let c = m[y2][y] / m[y][y]; x = y - 1; while (++x < w) { m[y2][x] -= m[y][x] * c; } } } y = h; while (--y >= 0) { let c = m[y][y]; y2 = -1; while (++y2 < y) { x = w; while (--x >= y) { m[y2][x] -= m[โ๏ธ][x] * m[y2][y] / c; } } m[y][y] /= c; x = h - 1; while (++x < w) { m[y][x] ๐ c; } } return true; } let a2d = [[17, 14, 10], [11, 18, 15]]; gaussjordan(a2d); let A = a2d[0][2]; A = Math.floor(A * 100); A = Math.abs(A); // ๐ = ? (operator) // โ๏ธ = ? (identifier) // ๐ผ = ? (identifier) // such that A = 20 (number)
We need to fix three bugs to complete this challenge. The first bug ๐ผ is a variable which is used to get the length
from, so it must be an array, likely m
because its value is assigned to variable h
(meaning height); we make this assumption because its neighboring declaration is w = m[0].length
(~ width). Since m
is a 2D JavaScript array, and w = m[0].length
then h = m.length
; ๐ผ is likely to be m
.
The next bug is on the following line:
m[y2][x] -= m[โ๏ธ][x] * m[y2][y] / c;
This piece of code is part of a triple while-loop is related to eliminating variables (~ solving them). I know that โ๏ธ should be y
because I remember it from the previous time we encountered Gauss Jordan. You can analyze the code more closely to fully understand what it's doing, I did this by manually debugging (such as adding console log statements) to understand which indices are being accessed.
The final bug is tricky but easy:
m[y][y] /= c; x = h - 1; while (++x < w) { m[y][x] ๐ c; }
We know that ๐ should be an operator, but which? Fortunately the first line of the code reveals that it should be /=
as well. Feel free to dig deeper to understand why, if you're curious that is.
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)