javaoperationdining-philosopher

Operation with "%" give an unexpected result


Im working in the Dining Philosophers Problem. For distribute the forks im using this loop that i found:

int philosophersNumber=5;

    for (int i = 0; i < philosophersNumber; i++) {
        philosophers[i] = new Philosopher(
                i, 
                forks[i], 
                forks[(i + 1) % philosophersNumber]
        );
    }


If i add some prints in the loop, the output looks like this:

----- PHILOSOHPER 0  ------
Right fork: 0
Left fork: 1
----- PHILOSOHPER 1  ------
Right fork: 1
Left fork: 2
----- PHILOSOHPER 2  ------
Right fork: 2
Left fork: 3
----- PHILOSOHPER 3  ------
Right fork: 3
Left fork: 4
----- PHILOSOHPER 4  ------
Right fork: 4
Left fork: 0

Well, my doubt is simple: Why is the result of (i+1) % 5 always the same as i+1 until i+1 is 5, that the result is 0? I suppose is related with the type of the variables, but i really don't know.


Solution

  • simple thing, % is modulo, which means the rest of an integer division. if for a%b, a < b -> a%b = a because everything is the rest. e.g.:

    1%3 = 1;
    2%3 = 2;
    3%3 = 0;
    4%3 = 1;
    5%3 = 2 etc.
    

    not a programmatic thing, its math.