# To write (4 - 1) instead of just 3 in the code: is it something people even do?

In the code below, I wrote (4 - 1) instead of just 3.

It looks kind of dumb, but I see logic in this type of decisions, it described in the comments. Don’t know: people do stuff like that or not?

Let me know, if link to the challenge is required, my question above is not about ‘how to solve this’, so I didn’t post the link right away.

``````function largestGridProduct(arr) {

let size = arr.length;
let maxProduct = 0;

for (let i = 0; i < size; i++) {

for (let j = 0; j < size; j++) {

//to check all horizontal products
if (j <= size - 4) {

let testProduct = arr[i][j];
for (let n = 1; n < 4; n++) {
testProduct *= arr[i][j + n];
}
if (testProduct > maxProduct) {maxProduct = testProduct;}

//nest another if block >>> also can check L to R diagonal products
if (i <= size - 4) {

let testProduct = arr[i][j];
for (let n = 1; n < 4; n++) {
testProduct *= arr[i + n][j + n];
}
if (testProduct > maxProduct) {maxProduct = testProduct;}
}
}

//to check all vertical and R to L diagonal products
//use symmetric if logic

if (i <= size - 4) {

let testProduct = arr[i][j];
for (let n = 1; n < 4; n++) {
testProduct *= arr[i + n][j];
}
if (testProduct > maxProduct) {maxProduct = testProduct;}

//in the below (4 - 1) expression used instead of (3) intentionally:
//all occurances of 4 in this code can be replaced with parameter
//if function will be modified to:
//find largest product of n adjacent numbers in NxN grid

if (j >= 4 - 1) {

let testProduct = arr[i][j];
for (let n = 1; n < 4; n++) {
testProduct *= arr[i + n][j - n];
}
if (testProduct > maxProduct) {maxProduct = testProduct;}
}
}

}

}

return maxProduct;
}
``````

Hard-coded ‘magic numbers’, no matter how you write them, are usually considered a bad idea.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.