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:
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?
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.