Search code examples
c++algorithmround-robin

Round robin algorithm in a loop


How round-robin algorithm can be implemented that runs in a loop for ever?

for (int i = 0; ;i++){
    roundRobinIndex = i % numberOfWorkers;
}

The problems with the way above is that integer overflow problem. It can also be implemented with checking the value of i:

for (int i = 0; ;i++){
    roundRobinIndex = i % numberOfWorkers;
    if i == maxNumber{
        i = 0;
    }
}

But this way seems ugly. Maybe there is more elegant way?


Solution

  • Why not ?

    int numberOfWorkers = 10
    int roundRobinIndex = numberOfWorkers - 1
    while(true){
        roundRobinIndex = (roundRobinIndex + 1) % numberOfWorkers
    }
    

    or with a for-loop

    for (int i = 0; ;i = (i + 1) % numberOfWorkers){
        roundRobinIndex = i;
    }
    

    We can now get rid of i