Circular Queue java not printing right - java

hey guys i have a problem when trying to print out the circular queue array
heres my code:
public class CircularQueue {
private int [] queue;
private int front, rear;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = 0;
rear = -1;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException {
if ( front == 0 && rear == -1 ){
throw new DSException();
}
queue[rear+1] = item;
rear = (rear+1)%queue.length;
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if ( front == 0 && rear == -1 ){
throw new DSException();
}
int temp = queue[front];
queue[front] = 0;
front = (front+1)%queue.length;
return temp;
}
// FILL IN:
// return the value at beginning of the queue
// throws DSException if no element in the queue
public int first () throws DSException {
return front;
}
// FILL IN:
// print the circular queue in the following format
// - print "+" before the value at the front
// - print "-" after the value at the rear
// - print "." for the places without valid element.
public void print () {
System.out.print(" <");
for ( int i = 0; i < queue.length; i++ ){
if ( front == 0 && rear == -1 ){
System.out.print("."+"\t");
} else if ( i == front ) {
System.out.print("+"+ queue[i]);
} else if ( i == rear ) {
System.out.print( queue[i]+ "-");
} else if ( i == front && i == rear) {
System.out.print("+"+ queue[i] +"-");
} else {
System.out.print( queue[i] );
}
}
System.out.print(">\n");
}
}
and here's the result
EMPTY:
<. . . . . >
ENQUEUE (0):
i am supposed to enqueue 0-4 and dequeue some element but it stops after enqueue 0.

A CircularQueue can be in 3 states whose invariants are given below :
Empty : front == -1 && rear == -1
Full : (rear+1)%queue.length == front
Neither empty nor full : Does not satisfy the conditions mentioned above
public class CircularQueue {
private int [] queue;
private int front, rear;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = -1;
rear = -1;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException,Exception {
if ( front == -1 && rear == -1 ){
front = 0;
rear = 0;
queue[rear] = item;
}
else if((rear+1)%queue.length == front) {
throw new Exception("Full");
}
else {
rear = (rear+1)%queue.length;
queue[rear] = item;
}
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if ( front == -1 && rear == -1 ){
throw new DSException();
}
else {
int ret = queue[front];
if(rear==front) {
rear = -1;
front = -1;
}
else {
front = (front+1)%queue.length;
}
return ret;
}
}
// FILL IN:
// return the value at beginning of the queue
// throws DSException if no element in the queue
public int first () throws DSException {
if(front==-1 && rear ==-1) {
throw new DSException();
}
return queue[front];
}
// FILL IN:
// print the circular queue in the following format
// - print "+" before the value at the front
// - print "-" after the value at the rear
// - print "." for the places without valid element.
public void print () {
if(front==-1 && rear == -1) {
for(int i=0;i<queue.length;i++) {
System.out.print(".");
}
}
else {
if(front<=rear) {
for(int i=0;i<=front-1;i++) {
System.out.print(".");
}
System.out.print("+");
for(int i=front;i<=rear;i++) {
System.out.print(queue[i]);
}
System.out.print("-");
for(int i=rear+1;i<=queue.length-1;i++) {
System.out.print(".");
}
}
else {
for(int i=0;i<=rear;i++) {
System.out.print(queue[i]);
}
System.out.print("-");
for(int i=rear+1;i<=front-1;i++) {
System.out.print(".");
}
System.out.print("+");
for(int i=front;i<=queue.length-1;i++) {
System.out.print(queue[i]);
}
}
}
}
}

This is my approach. But I am assuming here that the empty blocks in the array are initialized with zero, and that any valid entry would be non-zero. Also, it will print zeros in case the queue is partially filled.
public void print() {
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
System.out.println("In order from latest to oldest");
int i = front;
while (i < array.length) {
System.out.print(array[i] + " ");
i++;
}
i = i % array.length;
if(array[i] != 0) {
while(i < front) {
System.out.print(array[i] + " ");
i++;
}
}
}
}

Problem with circular arrays and front/rear indices is that 'full' and 'empty' are indistinguishable. You will have to add a boolean 'empty', which is initially true, and is used in the tests.
private int [] queue;
private int front, rear;
private boolean empty;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = 0;
rear = -1;
empty = true;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException {
if (!empty && (front - rear + queue.length) % queue.length == 1){
throw new DSException();
}
queue[rear+1] = item;
rear = (rear+1)%queue.length;
empty = false;
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if (empty){
throw new DSException();
}
int temp = queue[front];
queue[front] = 0;
front = (front+1)%queue.length;
empty = (front - rear + queue.length) % queue.length == 1;
return temp;
}

Related

Circular queue array implementation

Im trying to create a waiting list which will hold names of customers in a static array when the main array is full.and When the main array gets an EMPTY slot the first customer in the waiting list array will fill up the EMPTY slot of main array and the added element will be removed Im trying to create this using circular queue implementation.following the FIFO(First in first out) system
This is the circular queue implementation I have come up with
public class CQueue {
int SIZE = 4;
int front, rear;
int items[] = new int[4];
void initialize (String[]task) {
for (int i = 0; i < task.length; i++) {
task[i] = "FULL";
}
}
CQueue() {
front = -1;
rear = -1;
}
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
if (front == rear + 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (front == -1)
front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
return (element);
}
}
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
System.out.println("Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE)
System.out.print(items[i] + " ");
System.out.println(items[i]);
System.out.println("Rear -> " + rear);
}
}
This the delete method which will take user input to delete the element from task array and add the first come element of queue.
void deleteArr(String task[]) {
CQueue q = new CQueue();
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
int element = items[front];
task[NUM]=Integer.toString(element);
q.deQueue();
q.display();
}
The main method
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue();
q.initialize(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
while (true) {
q.deleteArr(task);
for (int j = 0; j < task.length; j++) {
System.out.println(task[j]);
}
}
}
I am stuck on how to add the queue element to the task array when a task array is deleted
I'd recommend you to check if front>=0 in deteleArr function. Also you should use the queue instance defined in main, and not a new instance:
void deleteArr(String task[]) {
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
if(front>=0) {
task[NUM]=Integer.toString(items[front]);
}
this.deQueue();
}
If you want, you can use the following display queue function:
void display() {
int i;
System.out.println("Print queue");
System.out.println("===========");
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
for (i = front; i <= rear; i++) {
System.out.println("item["+i+"]: " +items[i]);
}
System.out.println("Rear -> " + rear);
}
System.out.println("============");
}
And you can use this another function to display the task array:
public static void printTaskArray(String task[]) {
System.out.println("Print task[]");
System.out.println("============");
if (task.length==0) {
System.out.println("Empty task");
} else {
for (int j = 0; j < task.length; j++) {
System.out.println("task["+j+"]: "+task[j]);
}
}
System.out.println("============");
}
With this encapsulation you can change your main as follows:
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue ();
q.initialize(task);
printTaskArray(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
printTaskArray(task);
q.display();
while (true) {
q.deleteArr(task);
printTaskArray(task);
q.display();
}
}
I hope this help you.

Dequeues in Java using arrays + odd and even numbers

I'm having some trouble with my programming exercise in which I should implement dequeues using arrays.
I already got the operations I need but after the implementation you should run through the numbers 1-20 and insert the even numbers at the end of the dequeue and the odd numbers add the beginning.
After that you should use the method removeFront to remove all numbers in the list and should print them on the console.
There is also the hint that the correct output is: (19,17,15...,1,2,4,...,20).
My problem now is that the number 1 is missing in the list and instead it prints out a null value as the first item to be removed.
public class Dequeues<E> {
private final int max;
private int head;
private int tail;
private E[] deque;
private int counter;
public Dequeues(int max) {
this.max = max;
deque = (E[]) new Object[max];
this.head = 0;
this.tail = 0;
this.counter = 0;
}
public boolean isEmpty (){
return (counter == 0);
}
public boolean isFull() {
return(counter>= max);
}
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[head--] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public void addBack(E x){
if(!isFull()) {
if(tail == deque.length-1) {
tail = 0;
deque[tail] = x;
} else {
deque[tail++] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public E removeFront(){
if(!isEmpty()) {
E ret = deque[head];
deque[head++] = null;
if(head >= deque.length) {
head = 0;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public E removeBack(){
if (!isEmpty()) {
E ret = deque[tail];
deque[tail--] = null;
if(tail < 0) {
tail = deque.length-1;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public static void main (String [] args) {
Dequeues test = new Dequeues(20);
for (int i = 1; i <= test.deque.length; i++) {
if(i % 2 == 0) {
test.addBack(i);
} else if(i % 2 == 1) {
test.addFront(i);
}
}
System.out.println("Use of removeFront and output of the values: ");
for (int i = 0; i < test.deque.length; i++) {
System.out.print(test.removeFront() + " ");
}
}}
Output is the following:
Use of removeFront and output of the values:
null 19 17 15 13 11 9 7 5 3 2 4 6 8 10 12 14 16 18 20
You just simply wrong used -- operator.
Right implementation of the addFront method should be:
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[--head] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
So, the difference is here deque[--head] = x;
--head means reduce head value by one and then use it.
head-- means use value head and then reduce its value
Your situation was:
head = deque.length-1; head == 19
head != 0 and you go to the else statement. head value = 19. You used head-- and got again 19 and decremented it by one, but had to use --head.

CircularArrayQueue implementation Java

I am trying to implement a CircularArrayQueue. I've been given a JUnit test which my queue must pass.I suppose I am doing something wrong with the front and rear pointers. How should i approach learning data structures and algorithms ?
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue {
private Integer[] array;
// initial size of the array
private int N;
private int front;
private int rear;
public CircularArrayQueue() {
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size) {
this.N = size;
array = new Integer[N];
front = rear = 0;
}
// enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in) {
if (rear == N) {
if (front == 0) {
resize();
array[rear] = in;
rear++;
} else {
array[rear] = in;
rear = 0;
}
} else {
array[rear] = in;
rear++;
}
}
public void resize() {
Integer[] temp = new Integer[array.length * 2];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
temp = array;
}
// dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The queue is full");
}
int headElement = array[front];
if (front == N) {
array[front] = null;
front = 0;
} else {
array[front] = null;
front++;
}
return headElement;
}
#Override
public int noItems() {
return N - getCapacityLeft();
}
#Override
public boolean isEmpty() {
return (getCapacityLeft() == N);
}
// return the number of indexes that are empty
public int getCapacityLeft() {
return (N - rear + front) % N;
}
}
Your initialization is absolutely fine, and we do start with:
front = rear = 0;
Befor adding an item to the Q, we modify rear as
rear = (rear + 1) % N;
The % allows us to maintain the circular property of the queue. Also you must be wondering that if we modify rear before adding any item, then 0 index is left empty, well we have to compromise here with one array item being left blank, in order to have correct implementations for checking of isEmpty() and isFull() functions:
That said, the correct code for isEmpty() is:
#Override
public boolean isEmpty()
{
return front == rear;
}
You should also have a function isFull() like:
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
Also the line temp = array; in your resize() should be array = temp; and you must also update the value of N after calling resize().
Hence, the correct code is:
import java.util.NoSuchElementException;
public class CircularArrayQueue implements MyQueue
{
private Integer[] array;
//initial size of the array
private int N;
private int front;
private int rear;
private int count = 0;//total number of items currently in queue.
public CircularArrayQueue()
{
this.N = 10;
array = new Integer[N];
front = rear = 0;
}
public CircularArrayQueue(int size)
{
this.N = size;
array = new Integer[N];
front = rear = 0;
}
//enqueues an element at the rear of the queue
// if the queue is already full it is resized, doubling its size
#Override
public void enqueue(int in)
{
count++;
if (isFull())
{
resize();
rear = (rear + 1) % N;
array[rear] = in;
}
else
{
rear = (rear + 1) % N;
array[rear] = in;
}
}
public void resize()
{
Integer[] temp = new Integer[array.length*2];
N = array.length*2;
for(int i=0; i<array.length; i++)
{
temp[i] = array[i];
}
array = temp;
}
//dequeues an element
// if the queue is empty a NoSuchElement Exception is thrown
#Override
public int dequeue() throws NoSuchElementException
{
if(isEmpty())
{
throw new Exception("The queue is empty");
}
front = (front + 1) % N;
int headElement = array[front];
count--;
return headElement;
}
#Override
public int noItems()
{
return count;
}
#Override
public boolean isEmpty()
{
return front == rear;
}
#Override
public boolean isFull()
{
return front == ((rear + 1) % N);
}
//return the number of indexes that are empty
public int getCapacityLeft()
{
return N - 1 - count;
}
}

method to insert/append elements in array list

I am not sure if I am implementing the insert or append correctly but I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1 at AListInt.insert(AListInt.java:81) // listArray[i+1] = listArray[i]; at ListTest.main(ListTest.java:52) // list.insert(i);
Also I cannot use java.util.ArrayList
Here is the code and classes for it:
class:
public class AListInt {
int [] listArray;
int listSize;
int curr; // current position
AListInt() {
listSize = 0;
// note that curr = -1 when listSize = 0
curr = -1;
listArray = new int [2];
}
public int getValue () throws DSException {
return listArray[curr];
//returns the value of current position
//throw exception when there are no elements in the list
}
public int length() {
return listSize;
//return # of elements in the list
}
public int currPos() {
return curr;
//return current position.
}
public void moveToPos ( int pos ) throws DSException {
curr = pos;
//move the current position to pos
//throw exception if pos is not a valid position
}
public void moveToStart () throws DSException {
curr = 0;
//move the current position to the start of the list
//throw exception if no elements are in the list
}
public void moveToEnd () throws DSException {
curr = listSize;
//move the current position to the end of the list
//throw exception if no elements are in the list
}
public void prev () throws DSException {
if(curr != 0)
{
curr--;
}
//move current position to the previous element
//throws exception if the previous position is not legal or
// if there are no elements in the list
}
public void next () throws DSException {
if(curr < listSize)
{
curr++;
}
//move current position to the next element
//throws exception if the next position is not legal or
// if there are no elements in the list
}
public void insert ( int item ) {
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
listArray[curr] = item;
listSize ++;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
}
listArray = temp;
// inserts item to the current position
// if not enough memory, double the size of listArray
}
public void append ( int item ) {
listArray[listSize++] = item;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
listArray = temp;
}
// inserts item to the end of the list
// if not enough memory, double the size of listArray
}
public int remove () throws DSException {
if((curr < 0)||(curr > listSize))
{
return -1;
}
int item;
item = listArray[curr];
for(int i = curr; i < listSize - 1; i++)
{
listArray[i] = listArray[i+1];
}
listSize --;
return item;
//removes the element at the current position
//returns the removed element
}
public void clear() {
listSize = 0;
curr = -1;
//reset size. Set current position to be -1
}
public boolean find ( int val ) {
for(int i = 0; i > listSize; i ++)
{
if(listArray[i] == val)
{
return true;
}
}
return false;
//searches for val in the list
//returns true if found and false if not found
}
public void print () {
System.out.print("<");
for(int i = 0; i < listSize; i++)
{
System.out.print(listArray[i]);
if(listSize == -1)
{
System.out.print("-1");
}
}
System.out.print(">");
//outprint the list
}
}
exception:
public class DSException extends Exception {
public DSException() {
}
public DSException(String msg) {
super(msg);
}
}
main:
public class ListTest {
public static void main ( String[] args ) {
try {
AListInt list = new AListInt();
list.print();
// test length()
System.out.println ( list.length() );
// test currPos()
System.out.println ( list.currPos() );
// insert some numbers
for ( int i = 0; i < 4; i++ ) {
list.append(i);
list.print();
}
list.moveToPos(0);
list.print();
list.moveToEnd();
list.print();
// test getValue()
System.out.println ( list.getValue() );
System.out.println ( "remove: " + list.remove() );
list.print();
list.moveToStart();
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
list.clear();
list.print();
list.clear();
list.print();
System.out.println ( "find 0 : " + list.find ( 0 ) );
for ( int i = 0; i < 4; i++ ) {
list.insert(i);
list.print();
}
for ( int i = 0; i < 5; i++ ) {
System.out.println ( "find " + i + " : " + list.find ( i ) );
list.print();
}
list.next();
list.print();
list.insert ( -9 );
list.print();
list.append ( -2 );
list.print();
list.moveToEnd();
list.insert ( -1 );
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
} catch ( DSException e ) {
e.printStackTrace();
}
}
}
You reading outside the Array. in
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
if i = listSize -1, then listArray[i+1] is listArray[listSize], which is out of bounds, since arrays go from 0 to length -1
EDIT:
But since listArray has an initial size of 2, and you double the size at each insert you get away with that. However, at the first insert curr is -1, and since the termination is i >= curr, the loop will be entered and you will read listArray[-1] (Out of bounds)
it's gotta be listArray[i]=listArray[i-1]
because you are shifting the position of listArray[i-1] to the position of listArray[i]

My queue fails to display when I remove then add an item

I modified a program which creates a Queue and then add or remove items to it.
The problem in my code is that after I remove one item, and then add an item it goes into infinite loop and I'm not sure how to prevent it from happening.
My goal is to modify display() method only.
This is how I display Queue:
public void display()
{
int i = front;
do {
if (maxSize == nItems)
{
if (i == size())
i = 0;
System.out.print(queArray[i++] + " ");
}
else if (maxSize < nItems)
{
System.out.print("Too many queue items!");
break;
}
else
maxSize = nItems;
}
while (i != rear + 1 && !isEmpty());
}
This is how I add and remove items:
public void insert(long j) // put item at rear of queue
{
if(rear == maxSize-1) // deal with wraparound
rear = -1;
queArray[++rear] = j; // increment rear and insert
nItems++; // one more item
}
public long remove() // take item from front of queue
{
long temp = queArray[front++]; // get value and incr front
if(front == maxSize) // deal with wraparound
front = 0;
nItems--; // one less item
return temp;
}
Here is the source code for the same.
import java.util.Arrays;
public class Queue {
private int enqueueIndex;// Separate index to ensure enqueue happens at the end
private int dequeueIndex;// Separate index to ensure dequeue happens at the
// start
private int[] items;
private int count;
// Lazy to add javadocs please provide
public Queue(int size) {
enqueueIndex = 0;
dequeueIndex = 0;
items = new int[size];
}
// Lazy to add javadocs please provide
public void enqueue(int newNumber) {
if (count == items.length)
throw new IllegalStateException();
items[enqueueIndex] = newNumber;
enqueueIndex = ++enqueueIndex == items.length ? 0 : enqueueIndex;
++count;
}
// Lazy to add javadocs please provide
public int dequeue() {
if (count == 0)
throw new IllegalStateException();
int item = items[dequeueIndex];
items[dequeueIndex] = 0;
dequeueIndex = ++dequeueIndex == items.length ? 0 : dequeueIndex;
--count;
return item;
}
#Override
public String toString() {
return Arrays.toString(items);
}
}

Categories

Resources