Reputation: 31
I have a function that should take an (n*n) grid as an argument and output the maximum product of 4 nos. of all rows. (A part of project Euler problem 11). When I try to run the code it gives me,
TypeError: Cannot read property 'length' of undefined
What am I doing wrong here? (I am a beginner so plz tell me if I have any silly mistakes.)
Here is my code:
const grid = [
[40, 17, 81, 18, 57],
[74, 4, 36, 16, 29],
[36, 42, 69, 73, 45],
[51, 54, 69, 16, 92],
[7, 97, 57, 32, 16]
];
function largestGridProduct(arr) {
let product = 1 , maxProduct = 1;
for(let i=0 ; i<arr.length ; i++){
for(let j=0 ; j<arr.length-3 ; j++){
product = grid[i][j] * grid[i][j+1] * grid[i][j+2] * grid[i][j+3];
if(product > maxProduct){
maxProduct = product;
}
}
}
return maxProduct;
}
console.log(largestGridProduct(grid));
So what am i doing wrong here ?
Upvotes: 0
Views: 64
Reputation: 17
working like this :)
if(product > maxProduct){
return product = maxProduct;
}
return maxProduct;
}
}
}
Upvotes: 0
Reputation: 31
It was a silly mistake I was using variable name 'grid' instead of 'arr' inside the function. BTW thanks everyone. Ok.Here is my working code :-
const grid = [
[40, 17, 81, 18, 57],
[74, 4, 36, 16, 29],
[36, 42, 69, 73, 45],
[51, 54, 69, 16, 92],
[7, 97, 57, 32, 16]
];
function largestGridProduct(arr) {
let product = 1 , maxProduct = 1;
for(let i=0 ; i<arr.length ; i++){
for(let j=0 ; j<arr.length-3 ; j++){
product = arr[i][j] * arr[i][j+1] * arr[i][j+2] * arr[i][j+3];
if(product > maxProduct){
maxProduct = product;
}
}
}
return maxProduct;
}
console.log(largestGridProduct(grid));
Upvotes: 0
Reputation: 7429
You're not returning anything in the function...
By the way, you can make it easier.
See this:
[
[40, 17, 81, 18, 57],
[74, 4, 36, 16, 29],
[36, 42, 69, 73, 45],
[51, 54, 69, 16, 92],
[7, 97, 57, 32, 16]
].reduce((max, a2) => {
const val = a2.reduce((a, b) => {
return Math.max(a, b);
});
return Math.max(val, max);
}, 0)
It's using arrow functions (es6) and array reduce. This returns the max of all the input arrays.
Upvotes: 2