Help trying to understand modulo operation in circular array

14,284

Solution 1

I think you're a bit conofused as to what the modulo operation does. It gives the integer remainder after a division. So from your example.

4 % 5 = 4 (because 4/5 is 0, with a remainder of 4)

AND

8 % 5 = 3 (because 8/5 is 1 with a remainder of 3)

Without seeing the rest of your implementation, its a bit difficult to explain further why modulo is being used, but it looks like its basically being used to ensure that your circular array wraps around. i.e. when you hit the end of the array (say index 7, of an array with MAX size 8, the next value you would want would be the first element, which would be 8%8 or 0).

Solution 2

integer arithmetic will only result in integers. While modulo is related to division it is not division.

a % b is the same as (a - a / b * b) 

As loops it is the same as. (Assuming b is positive)

int result = a;
while(a >= b) a -= b;
while(a + b <= 0) a += b;

However for rare = (rare + 1) % MAX, it is the same as.

rare = (rare == MAX - 1 ? 0 : rare + 1);
Share:
14,284
JBoy
Author by

JBoy

Beginner java/jsp developer

Updated on June 28, 2022

Comments

  • JBoy
    JBoy almost 2 years

    i have a small issue trying to figure out how a modulo operation is being calculated. I am building up a queue, so i have a circular array. i cannot figure out how this modulo operation works.

    Given q: an array of Character of 5 elements length, The MAX constant gives the max length of the array "5" rare is an int which represents the first available spot in the array q

        public void enqueue(Character c)throws FullQueueException{
    
        if(size()== MAX -1){ //if only 1 place left, is full, throw exc 
    
            throw new FullQueueException("Queue is full");
        }
        q[rare]=c;  
        rare=(rare+1)%MAX;
    }
    

    Now, supposing that the rare "first empty spot" is three, what is the rare value going to be after the method has finished? this is what i dont get, rare=(rare+1)%MAX means rare=4%5 which gives rare=0,8.

    Same for method size:

    public int size() {
    
        return (MAX - front + rear) % MAX;
    }
    

    Given, front, an int variable which represents the first element in the array Suppose front is 1 and rare 4, so there are 3 elements in the array, so size is (5-1+4)%5 which is 8%5 which gives 1.6, while the actual size is 3 Any suggestion? this might be more math then java but probably some of you came across the same doubt before. Thank you!