Reputation: 5155
I'm trying to solve this problem that I came across, struggling to get to solution:
Problem:
const arr = [4, [3,1],1,[[2], 1]];
We need to sum all the elements * depth of the element.
For example, for [4, [3,1],1,[[2], 1]] = 4*1 + 3*2 + 1*2 + 1*1 + 2*3 + 1*2 = 21
This is my solution, however, I am not getting correct value. Can someone solve this using ES5 and ES6?
const b = [4, [3,1],1,[[2], 1]]; // 4*1 + 3*2 + 1*2 + 2*3 + 1*2 + 1*1
function addNormalize(arr, sum=0, depth=1) {
for(let i=0; i< arr.length; i++) {
const cur = arr[i];
if (Array.isArray(cur)) {
depth+=1;
addNormalize(cur, sum);
} else {
sum+=cur * depth;
}
}
return sum;
}
console.log(addNormalize(b))
Upvotes: 1
Views: 146
Reputation: 92450
You can do this pretty cleanly with reduce()
const b = [4, [3,1],1,[[2], 1]];
function addNormalize(arr, depth = 1){
if (arr.length == 0) return 0
return arr.reduce((a,item) => a + (Array.isArray(item) ? addNormalize(item, depth+1) : depth * item), 0)
}
console.log(addNormalize(b))
Upvotes: 2
Reputation: 20805
I made some corrections to your code, you were trying to calculate the result by passing a "reference" and that can't be done in javascript with primitives, also you were not passing the depth to the recursive call.
const b = [4, [3,1],1,[[2], 1]]; // 4*1 + 3*2 + 1*2 + 1*1 + 2*3 + 1*2
function addNormalize(arr, depth=1) {
let sum=0;
for(let i=0; i< arr.length; i++) {
const cur = arr[i];
if (Array.isArray(cur)) {
sum += addNormalize(cur, depth+1);
} else {
sum+=cur * depth;
}
}
return sum;
}
console.log(addNormalize(b))
Upvotes: 1
Reputation: 4647
The reason why your code is not working is extremely simple. Primitive value like string, boolean, int, float etc. are not passed by reference
but value. This means value is copied as an immutable value(you can change the original value in another function scope)
You should either receive the value returned by the recursive function called in:
if (Array.isArray(cur)) {
depth+=1;
sum += addNormalize(cur, sum);
}
or change sum to an object so that sum is passed by reference.
Upvotes: 1