This was fun There are simpler approaches using a temporary array, but makes a nice challenge trying to do it without (it's possible that it would end up faster too, but how big an array we'd need in order to notice… I'm not sure).
Have a gander and see what you think:
// need to expand the array size by a variable amount, so that its original elements are repeated evenly // original array [A,B,C], expanded by 4 should return: [A,A,A,B,B,C,C] i[]@array = {1,2,3,4,5}; int expand_count = chi("expand"); int input_len = len(i[]@array); int output_len = input_len + expand_count; // vex may well optimize this for us, but still a good habit to // resize an array only once if we know the desired array size in advance // rather than call append() or insert() inside a loop resize(i[]@array, output_len); for(int i=input_len; i>0; i--) { // we want to write out the i-th input value to the highest 'unwritten' // output index until i doesn't fit in our unwritten range int inner_loop = output_len/i; for(int j=0; j<inner_loop; j++) { // write the i-th input value to the end of the unwritten portion // of the output array i[]@array[output_len-1] = i[]@array[i-1]; // reduce the size of the unwritten portion output_len--; } }
I haven't had a change to properly untangle what was up with your original code, but my first guess is that you were getting bitten by the data dependencies between ‘count’ and 'i@array' inside the loop.
Cheers!