• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Function that sums up all integers from a deeply nested array

Resolved: Function that sums up all integers from a deeply nested array

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have an issue here, I’m trying to create a function that sums up all integers from a deeply nested array, but it’s failing an unit test, which means something is not right. Here is my function:
When c is called, your call stack will contain all the memory for variables used in c. When c calls b, all the memory for variables used in b are added to the stack. When b calls a all the memory for variables used in a are added to the stack. When a finishes executing (so when you get to ‘some code’), variables related to a are deallocated and removed from the stack.
The problem you have here is that every time your function recursively calls itself, more memory is being allocated onto the stack. to stop this kind of code using up all the system memory, the runtime limits how big the stack can get – which is why you are hitting this error.
To pass this test, you need a solution which doesn’t call itself every time it hits an array within an array. Here’s my solution, effectively using an array as a buffer; each time I hit a nested array I add it to the buffer. Once I finish processing the outer array, I then check if there is any arrays left in the buffer.

export const arraySum = (arr) => {
let sum = 0;
const buffer = [arr];
while (buffer.length > 0) {
const next = buffer.shift();
for (let i = 0; i < next.length; i++) { if (typeof next[i] === "number") sum = sum + next[i]; else if (Array.isArray(next[i])) buffer.push(next[i]); } } return sum; }; [/code]

If you have better answer, please add a comment about this, thank you!

algorithm javascript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: std::regex_replace to replace multiple combinations

26/03/2023

Resolved: How can I copy files using the ansible.builtin.copy module and avoid conflicting file names?

26/03/2023

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.