Search code examples
algorithmiterationpseudocode

How to increment and decrement between two values


This is embarrassing, but:

Let say I want to add 1 to x until it reaches 100. At that point I then want to subtract 1 from x until it reaches 1. Then I want to add 1 to x until it reaches 100, and so on.

Could someone provide some simple pseudocode to this question that is making me feel especially dumb.

Thanks :)


EDIT 1

Apologies! I made my example too simple. I actually will be incrementing using a random number at each iteration, so responses that require (x == 100) would not work as x will surely go above 100 and below 1.


Solution

  • int ceiling = 100;
    int floor = 1;
    int x = 1;
    int step = GetRandomNumber(); //assume this isn't 0
    
    while(someArbitraryCuttoffOrAlwaysTrueIDK) {
        while(x + step <= ceiling) {
            x += step;
        }
        while(x - step >= floor) {
            x -= step;
        }
    }
    

    Or, being more concise (at the risk of being less clear):

    while(someArbitraryCuttoffOrAlwaysTrueIDK) {
        while((step > 0  && x + step <= ceiling) || (step < 0 && x + step >= floor)) 
        {
            x += step;
        }
        step = step * -1;
    }
    

    Alternatively:

    while(someArbitraryCuttoffOrAlwaysTrueIDK) {
        if((step > 0  && x + step > ceiling) || (step < 0 && x + step < floor)) 
        {
            step = step * -1;
        }
        x += step;
    }