java - Help trying to understand modulo operation in circular array -


i have small issue trying figure out how modulo operation being calculated. building queue, have circular array. cannot figure out how modulo operation works.

given q: array of character of 5 elements length, max constant gives max length of array "5" rare int represents first available spot in array q

    public void enqueue(character c)throws fullqueueexception{      if(size()== max -1){ //if 1 place left, full, throw exc           throw new fullqueueexception("queue full");     }     q[rare]=c;       rare=(rare+1)%max; } 

now, supposing rare "first empty spot" three, rare value going after method has finished? dont get, rare=(rare+1)%max means rare=4%5 gives rare=0,8.

same method size:

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

given, front, int variable represents first element in array suppose front 1 , rare 4, there 3 elements in array, size (5-1+4)%5 8%5 gives 1.6, while actual size 3 suggestion? might more math java of came across same doubt before. thank you!

i think you're bit conofused modulo operation does. gives integer remainder after division. example.

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

and

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

without seeing rest of implementation, bit difficult explain further why modulo being used, looks being used ensure circular array wraps around. i.e. when hit end of array (say index 7, of array max size 8, next value want first element, 8%8 or 0).


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -