Help needed in Chunky Monkey Problem

I tried to solve chunky monkey problem. Here is what I have tried:

function chunkArrayInGroups(arr, size) {
  var ans = [];
  var count = 0;
  times = Math.round(arr.length/size);
  for(var i = 0; i < times; i++){
    var temp = [];
    for(var j = 0; j<size;j++){
      if(count < arr.length){
        temp.push(arr[count]);
      }
      count++;
      console.log(temp);
    }
    ans.push(temp);
  }
  // push all those broken pieces into another array
 
  return ans;
}

I get all test cases passing, just two are failing:

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]].
and
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].

Please guide me how I tackle those two scenarios. Thanks.

Try Math.ceil instead of round

2 Likes

@chiquito83 Thanks a lot. That solved it!

 ******Chunky Monkey (My Solution)*******

function chunkArrayInGroups(arr, size){

var array = []; var splicedArray;

for(var i = 0; i < arr.length; i+size){

splicedArray = arr.splice(i,size);

array.push(splicedArray);

}

return array;

}

I can’t figure out why is your code working. Please explain me .
Let say we run this chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3),
After 1st time loop, arr is spliced. So arr = [3, 4, 5, 6], i = 3.
When 2nd time loop, arr.splice(3, size). So doesn’t this gonna splice from index 3 which value is 6? Why it splice from index 0 which value is 3?

Sorry for my bad english!

I did some debugging on ahsanwaseem’s solution, and I am finding that the variablei is not changing in the for-loop as well, it is stuck at 0 which is why it works as a solution. You can change his for loop to be:
for(let i =0; i<arr.length;)
and it will still work as a solution, even thought logically it shouldn’t.

His code is effectively the same as this. For loop is just an over-glorified while loop - in this case over-glorified without need.

function chunkArrayInGroups(arr, size) {
	var array = [];
	//var splicedArray;

	// for(var i = 0; i < arr.length; i+size){
	// console.log(i)
	// splicedArray = arr.splice(i,size);

	// array.push(splicedArray);

	// }

	while (arr.length > 0) {
		array.push(arr.splice(0, size));
	}

	return array;
}
1 Like