Chunkey monkey feedback request

My first intention was to solve it recursively.

The thing is: i accidentally solved it with iteration :upside_down_face: when trying to think recursively.
That was relatively quick.

And then I was trying to solve it recursively, and it was not so quick and easy, though I’ve managed to do that

I have some mindset going on: my brain often throws at me iteration approach by default. Not sure how to feel about that.

Iteration at the top, recursion at the bottom

//Iteration
function chunkArrayInGroups(arr, size) {  
  let result = [];
  for (let i = 0; i < arr.length; i+=size) {
    result.push(arr.slice(i, size + i))
  }
  return result;  
}

//Recursion
function chunkArrayInGroups(arr, size) {
  //boundary conditions for size
  if (size < 1) {
    return [];
  }
  //recursion
  //base case
  if (arr.length <= size) {return [arr];}
  //recursive step
  else {
    return [arr.slice(0, size), ...chunkArrayInGroups(arr.slice(size) , size)];
    
  }
}

The first is how I’d solve it. The second… it is important to understand recursion, but it’s rarely the right tool for the job.

1 Like

I typed in Google:
how to choose between recursion and iteration

And there are too many contradictory statements about this:

Iteration is faster and more space-efficient than recursion.

Don’t know about this one


When should you choose a recursive algorithm over an iterative algorithm? In situations where the recursive algorithm is easier to design. Specifically, situations where a problem can be broken down into small repetitions of very similar problems.

This doen’t make sense to me. Iteration also can deal with small repetitions


Why to use recursion

Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but doesn’t necessarily reduce space requirements or speed of execution).
Reduces time complexity.
Performs better in solving problems based on tree structures.

Trees are some kind of graph if I am not mistaken… They are talking about DFS/BFS algorithms, when we are searching for some node in the tree?
Also not sure about ‘adds clarity’ part.

Generally, fixed length iterations are more effecient and easier to read than recursion, yes.

You really want recursion for problems that have a nested structure. The steamroller challenge is a good example. Problems with tree traversal are another good example.

1 Like