Increase integer values within a integer array

Rooney

New Member
#1
I have question regarding increase the values within a one dimensional integer array. For example an array like [0,0,0,0] and I want to increase the farthest right position in the array by one so [0,0,0,1].

I want to keep increase this value to a set limit for example [0,0,0,3] and once it reaches that limit I want to increase the value of the integer to the direct left by 1 and reset the farthest right so [0,0,1,0] then repeat all over again to eventually get an output like this

[0,0,1,3] -> [0,0,3,3] -> [0,1,0,0]

Please note I did skip a few steps but every time I want to increase only by 1.

This is what I want to use for DFS. Also the size of the array can change but only when it is first created so the size maybe 20 one run and another run it could be 5 so using a bunch of for loops wouldn't work.

I am also not looking for the answer just tip in the right direction.
 

Admin

Administrator
Thành viên BQT
#2
Something like
Mã:
function IncrementOne(int array[], int maxArrayInt, int maxArrayLength) {
    int i = maxArrayLength - 1;
    bool c = false;
    do {
       int p = array[i];
       p = p + 1;
       c = p > maxArrayInt;
       if(c)
          array[i] = 0;
       else
          array[i] = p;
       i = i - 1;
    }
    while(c && i >= 0)
}
IncrementOne function is called (ie IncrementOne([0,0,3,3], 4, 3) for your example). maxArrayLength can be automatically derived if you want.

Array runs at least once in the do / while loop

In the do while loop, get right most value in array

Increment value

Check if value is greater than maxArrayInt

If it is, then set right most value to 0 and run loop once more

If it isn't, then set right most value with incremented value and exit loop
 
Top