Chunky Monkey (under Basic Algorithm Scripting) question

Chunky Monkey (under Basic Algorithm Scripting) question
0

#1

Hi, I manage to complete this challenge but I didn’t manage to use the array.push() method. I have included my code below :

/** setup

function chunkArrayInGroups(arr, size) {
// Break it up.
var totalArr = [];

if (arr.length/size <= 2) {
firstArr= arr.splice (0, size);
secondArr= arr;
totalArr = [firstArr, secondArr];
}

else if (arr.length/size <= 3) {
firstArr= arr.splice (0, size);
secondArr= arr.splice (0,size);
thirdArr = arr;
totalArr = [firstArr, secondArr, thirdArr]; }

else if (arr.length/size <= 4) {
firstArr= arr.splice (0, size);
secondArr= arr.splice (0,size);
thirdArr = arr.splice(0,size);
fourthArr= arr;
totalArr = [firstArr, secondArr, thirdArr, arr]; }

return totalArr;

}

chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);

**/ end setup

I feel like my code is not complete because if chunkArrayInGroups ([0, 1, 2, 3, 4, 5], 1), the result is only [].

Can anyone push me to the right direction to produce a better code for this challenge?

Many thanks in advance :slight_smile:


#2

Why do you want to avoid array.push()? Your method cannot scale up.


#3

What is any number divided by 1 equal to? You don’t have an else case to handle that. So it’s just passing you the empty array.

But as @soarer alluded, doing it this way will only solve as many test cases as you are able to think ahead to hard code in.


#4

Yea, I know that. It’s just that I can’t seem to find a way to use array.push() in my code.


#5

I’m stuck on this one as well. But I think you would want totalArr = [firstArr, secondArr];
to be where you have the array.push().


#6

Hi guys I wanted to share my solution. I used the splice method to split the array based on the size given and then push the spliced Array into a completely newArray. Tell me what you think.:slight_smile:

function chunkArrayInGroups(arr, size) {

var arraySize  = arr.length/size;

var newArray = [];

    for (var i = 0; i < arraySize ; i++){

        var subArray= arr.splice(0,size);

        newArray.push(subArray);

    }

return newArray;

}`

#7

@TTomaszito That looks pretty good, another option is to remember than for loops don’t need to increment by one:

function chunkArrayInGroups(arr, size) {
// Break it up.
var chunkArr = [];
for (var i=0; i < arr.length; i += size){
chunkArr = chunkArr.concat(Array.of(arr.slice(i, i + size)));
}
return chunkArr;

}


#8

@ChadKreutzer that’s interesting I never thought about other increments. Makes loads of sense thanks for the tip.


#9

Great solution TTomaszito!

If you want to force yourself to use “.slice” instead of “.splice” here is what you can do:

chunkArr.push(arr.slice(i*size+0, size*i+size));


#10

hey i did this dont know if the correct approach though(scalable)

function chunkArrayInGroups(arr, size) {
var multiD = [];

arr.map(function(element,index){
if(index % size === 0){
multiD.push(arr.slice(index,size+index));

}

});
//console.log(multiD);

return multiD;
}

chunkArrayInGroups([“a”, “b”, “c”, “d”], 2);


#11

I can see these posts are months old. I’m just starting through algorithms and using the forum to see better solutions (there is always more than one!)

thought a bit of refactoring will help to do away with concat & Array.of (and to bring in push)… since slice returns an array, using push will get us a two dimensional…

function chunkArrayInGroups(arr, size) {
// Break it up.
var chunkArr=[];
for(var index=0;index<arr.length;index+=size)
chunkArr.push(arr.slice(index,index+size));
return chunkArr;
}


#12

Good job getting past the challenge. :thumbsup:

Here is my code:


function chunkArrayInGroups(arr, size) {
  // An array to store the results
  results = [];
  // Divide the length of 'arr' by 'size' and 'ceil' it off to next number. 'round' is different from 'ceil'
  count = Math.ceil(arr.length/size);
  
  for (var i=0; i<count; i++){
  	// Push the sliced array to 'results'
  	results.push(arr.slice(0, size));
  	// Remove the sliced elements from the array and keep the rest
  	arr = arr.slice(size, arr.length);
  }
  return results;
}

#13

Here is my code in case you are curious, this took some trial and error but I finally got it. My first solution had a FOR loop and extra function, I wanted to clean it up so here it is:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  var len = arr.length;
  for (var i = 0; i < len / size; i++){
    newArr.push(arr.slice(0,size));
    arr.splice(0,size);
    console.log( 'Loop ' + i + ' :' +newArr );
    console.log( arr );
  }

  console.log( newArr );
  return newArr;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2);

#14

Thanks! I was really close to finish just like you, but I was slicing my array in wrong points. Your solution clarified some things up :slight_smile:


#15

Hi everyone, just want to thank you for posting your solutions. I managed to solve it but I didn’t use “slice”, only “push”. Somehow I got stuck in a line of thought and tried to get a solution no matter what. But seeing your elegant and concise solutions made me realize I should have approached it in a different way. And that’s really useful. Here’s my code:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var arrFinal = [];
  var arrToPush = [];
  var resetArr = 0;
  
  for( var i = 0; i < arr.length; i++){
      
      if (resetArr < size) {
        arrToPush.push(arr[i]);
        resetArr++;
        
        if (resetArr === size || i + 1 == arr.length){ // se exceder o size ou for a última posiçã
          arrFinal.push(arrToPush);
          arrToPush = [];
          resetArr = 0;
        }

      }

  }
  //console.log(arrFinal);
  return arrFinal;
}

chunkArrayInGroups(["a", "b", "c", "d"], 4);

#16

here’s my solution if anyone is interested. :slight_smile:

This thread was helpful in coming to my answer, so maybe it will continue to help others as they look for help

function chunkArrayInGroups(arr, size) {
          //Make segment picker beginning
          var sliceStart = 0;
          //Make segment picker end
          var sliceEnd = size;
          //Make answer array
          var outarr = [];
          ///Loop through array in increments of the size param
          for (var i = 0; i < arr.length; i = i + size) {
            //push the slices to the answer array
            outarr.push(arr.slice(sliceStart,sliceEnd));
            //Increment the segment pickers
            sliceStart += size;
            sliceEnd += size;
          }
          //Answer out
          return outarr;
        }

        chunkArrayInGroups(["a", "b", "c", "d"], 2);

#17

Here’s my solution, pretty simple. Not that the challenge is that simple, my code is.

function chunkArrayInGroups(arr, size) {
  var newArray = [];
  
  for(var i = 0; i < arr.length; i+=size){
    newArray.push(arr.slice(i,i+size));
  }
  return newArray;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

#18

I chose to use splice as well, but forgot to follow up with a sub-array! This was a huge help! Thanks!


#19
var newArray = [];
        
   while (arr.length){
    newArray.push(arr.splice(0, size));
   }
  return newArray;

#20

@andreyivanov86 I like your while loop, but keep in mind what is happening behind the scenes when you splice. The array which is spliced has to first remove the elements and then “rearrange” the array by moving indexes, etc… The performance hit is massive if the number of items in the array is large and the chunk size is small.

For example, I did some performance testing where I compared your version (with SPLICE) to my version (with SLICE). I first generated an array with just 100,000 integers and then passed the array and size of 2 to each function. My slice version was 2000% faster than your splice version. See my slice version below:

  var newArray = [];
  for (var i=0; i<arr.length; i+=size)
    newArray.push(arr.slice(i,i+size));
  return newArray;

For the size of arrays used in the challenge tests, it is difficult to see the performance difference, but when I used 1,000,000 items in array with size two, your splice version took 214,969 milliseconds ( 3.58 seconds) compared to my slice version which took only 148 milliseconds (0.148 seconds).

My only point in saying all of this is to be careful when using certain functions and be aware of the behind-the-scenes work being performed when using them. I like the elegance of using the while loop like you did, but not the efficiency of the function.