Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue with mod operation

Tags:

c++

queue

I'm studying fundamental of data structure (Queue) , so far I understand the flow of Queue but I don't understand whenever queue is applying with Mod operator. There a several question which confusing my brain. How to answer this question (refer to picture)?

Here the example of questions.

like image 567
Edie Avatar asked Feb 05 '26 00:02

Edie


2 Answers

The best method for handling circular queues is to draw them out. Since circles don't post very well with ASCII art, I'll use a linear array.

+---+---+---+---+---+  
|   |   |   |   |   |  
+---+---+---+---+---+  
  0   1   2   3   4  
                  ^  
                 Rear  

The REAR is at index 4.

Let's perform the operation step by step.
First: Add 1 to REAR. This makes REAR point beyond the array:

+---+---+---+---+---+  
|   |   |   |   |   |  
+---+---+---+---+---+  
  0   1   2   3   4   5   
                      ^  
                      Rear  

Applying the modulo operation, %, this will give us the remainder of 5 / 5 which is zero:

+---+---+---+---+---+  
|   |   |   |   |   |  
+---+---+---+---+---+  
  0   1   2   3   4     
  ^  
 Rear  

Thus the modulo operation wraps around the array, like a circle.

The next question is for you to solve. Remember draw the array or queue. You can use circles (think of a pie sliced or a pizza sliced).

Edit 1: Modulo details
The modulo operation will give a value in the range 0..N, when N is the divisor.

Given N == 4, here are some results for modulo:

Index result
0       0
1       1
2       2
3       3
4       0  --> The remainder of 4 / 4 == 0.
5       1
6       2
7       3
8       0  -->  The remainder of 8 / 4 == 0.
like image 98
Thomas Matthews Avatar answered Feb 08 '26 22:02

Thomas Matthews


Modulus returns the remainder of the two operands. For example, 4%2=0 since 4/2=2 with no remainder, while 4%3=1 since 4/3=1 with remainder 1. Since you can never have a remainder higher than the right operand, you have an effective "range" of answers for any modulus of 0 to (n-1). With that in mind, just plug in the numbers for the variables ((4+1)%5=? and (1+1)%4=?). Usually to find the remainder you would use long division, but one useful thing to remember is that any number divided by itself has a remainder of 0, and any number divided by a larger number will have a remainder equal to itself.

like image 26
IllusiveBrian Avatar answered Feb 08 '26 22:02

IllusiveBrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!