I've come across a way of implementing a circular array that represents a double ended queue.
Let the circular array have the following instance variables:
int[] array;
int front = 0;
int rear = -1;
int size = 0;
int capacity = x; // where x is a parameter in the constructor
The operations of the queue are:
dequeue - return array[front], increment front by 1,
enqueue - increment rear by 1, set array[rear] = value.
I have come to the conclusion that it is not possible to get the size of this queue by using the formula (front - rear + 1) % capacity. However, it is said that it's possible to get the size of the array using the same formula if we let the constructor set the capacity by:
BoundedQueue(int capacity) {
this.capacity = capacity + 1;
}
With this technique the array will never actually get full and the formula for giving the size of the queue should work (it is said).
However I can't figure out how these modifications to the queue would result in the formula returning the correct size of the queue? We're only making the array one size bigger than it actually is, and we're always leaving at least one element unused. Could someone with a better insight explain to me why these modifications will lead to (rear - front + 1) % capacity giving the correct size of the queue?
Thanks in advance!