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;
}
}
Related
I have generated a minheap to this file but I think something I have missed but I can't identify what are the things I have missed. I have missed something on --private void bubbleDown() { }-- section but I can't find what are the things missed by me.
private int default_size = 100; // how big the heap should be
private T[] array;
private int size;
public Heap() {
#SuppressWarnings("unchecked")
T[] tmp = (T[]) (new Comparable[default_size]);
array = tmp;
size = 0;
}
boolean isRoot(int index) { return (index == 0); }
int leftChild(int index) { return 2 * index + 1; }
int parent(int index) { return (index - 1) / 2; }
int rightChild(int index) { return 2 * index + 2; }
T myParent(int index) { return array[parent(index)]; }
T myLeftChild(int index) { return array[leftChild(index)]; }
T myRightChild(int index) { return array[rightChild(index)]; }
boolean hasLeftChild(int i) { return leftChild(i) < size-1; }
boolean hasRightChild(int i){ return rightChild(i) < size-1; }
private void swap(int a, int b) {
T tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
public boolean isEmpty() { return (size == 0); }
/* adding heap */
public void add(T value) {
if(size == default_size) throw new IllegalStateException("Full array");
array[size++] = value;
bubbleUp();
}
public void bubbleUp() {
if(size == 0) throw new IllegalStateException("Shape error");
int index = size - 1;
while(!isRoot(index)) {
if(myParent(index).compareTo(array[index]) <= 0) break;
/* else part */
swap(parent(index), index);
index = parent(index);
}
}
/* removing */
public T remove() {
if(isEmpty()) return null;
T res = array[0]; /* root */
array[0] = array[size-1];
size --;
bubbleDown();
return res;
}
// i think this section having wrong something
private void bubbleDown() {
int parent = 0;
int leftChild = 2*parent + 1;
int rightChild = 2*parent + 2;
int choice = compareAndPick(leftChild, rightChild);
while (choice != -1)
{
swap(choice, parent);
parent = choice;
choice = compareAndPick(2*choice+1, 2*choice+2);
}
}
private int compareAndPick(int leftChild, int rightChild)
{
if (leftChild >= default_size || array[leftChild] == null) return -1;
if (array[leftChild].compareTo(array[rightChild]) <= 0 || (array[rightChild] == null))
return leftChild;
return rightChild;
}
public void show() {
for(int i=0; i<size; i++)
System.out.print(array[i] + " ");
System.out.println("=======");
}
public static void main(String [] args) {
Heap<Integer> heap = new Heap<Integer>();
for(int i=0; i<10; i++) {
heap.add((Integer)(int)(Math.random() * 100));
heap.show();
}
System.out.println("You should see sorted numbers");
while(!heap.isEmpty()) {
System.out.print(heap.remove());
System.out.print(" ");
heap.show();
}
System.out.println();
}
}
this code used generics and min heap functions.. i need to identify what is the wrong thing did by me on bubbleDown() section
Explanation
The bubbleDown() method is not a different way to insert a node and move it to it's correct position in the Heap. When bubbleDown() is called it's job is to Heapify the Binary Tree from any state. So your attempt to write the method just by changing the condition from the bubbleUp() method isn't gonna help you.
Extra
Here is a video that can give you the idea of how bubbleDown is supposed to work.
public class ourStack1 {
private int elements[];
private int index; // indicate the next position to put a new data
private int size;
public ourStack1() {
elements = new int[10];
index = 0;
size = 0;
}
public void push(int value) {
if(size == 10) {
System.out.println("Stack is full, no push");
return;
}
elements[index] = value;
++index;
++size;
}
public int pop() {
if(size == 0) {
System.out.println("Stack is empty, no pop");
return -1;
}
int temp = elements[index - 1];
--index;
--size;
return temp;
}
public int peek() {
if(size == 0) {
System.out.println("Stack is empty, no peek");
return -1;
}
return elements[index - 1];
}
/*
public int mySize() {
// you know how to do this
}
*/
public static void main(String[] args) {
ourStack1 x = new ourStack1();
for(int i = 0; i < 10; ++i)
x.push(i);
for(int i = 0; i < 10; ++i)
System.out.println(x.pop());
}
}
I'm confused on how to overwrite the last element added to the full stack. I want to add element to replace the last element while not exceeding the array size[10]
public void replaceLast(int value) {
if (this.size > 0) {
this.pop();
}
this.push(value);
}
This is my Queue class. I have implemented it using arrays.
public class QueueUsingArray {
private int data[];
private int firstElementIndex;
private int nextElementIndex;
private int size;
public QueueUsingArray() {
data = new int[10];
firstElementIndex = -1;
nextElementIndex = 0;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
private void checkEmpty() throws QueueEmptyException {
if (size == 0) {
QueueEmptyException e = new QueueEmptyException();
throw e;
}
}
public int front() throws QueueEmptyException {
checkEmpty();
return data[firstElementIndex];
}
public int dequeue() throws QueueEmptyException {
checkEmpty();
int output = data[firstElementIndex];
size--;
data[firstElementIndex] = 0;
firstElementIndex = (firstElementIndex + 1) % data.length;
if (size == 0) {
firstElementIndex = -1;
nextElementIndex = 0;
size = 0;
}
return output;
}
public void enqueue(int element) {
if (size == data.length) {
int[] temp = data;
data = new int[data.length * 2];
int k = 0;
for (int i = firstElementIndex; i < temp.length; i++) {
data[k] = temp[i];
k++;
}
for (int i = 0; i < firstElementIndex; i++) {
data[k] = temp[i];
k++;
}
firstElementIndex = 0;
nextElementIndex = temp.length;
}
if (size == 0) {
firstElementIndex = 0;
}
data[nextElementIndex] = element;
size++;
nextElementIndex = (nextElementIndex + 1) % data.length;
}
}
Here is my QueueUse class.
public class QueueUse {
public static void main(String[] args) throws QueueEmptyException {
QueueUsingArray q=new QueueUsingArray();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.enqueue(70);
q.enqueue(80);
q.enqueue(90);
q.enqueue(100);
q.enqueue(110);
q.enqueue(120);
q.enqueue(130);
q.enqueue(140);
q.enqueue(150);
q.enqueue(160);
q.enqueue(170);
q.enqueue(180);
q.enqueue(190);
q.enqueue(200);
q.enqueue(210);
q.enqueue(220);
q.enqueue(230);
q.enqueue(240);
q.enqueue(250);
q.enqueue(260);
q.enqueue(270);
q.enqueue(280);
q.enqueue(290);
q.enqueue(300);
System.out.println("All elements");
for(int i=0;i<q.size();i++){
try {
System.out.println(q.dequeue());
} catch (QueueEmptyException e) {
System.out.println("Sorry");
}
}
}
}
My output is not complete. Output is not showing all the elements in my queue. What is the error. Output is only showing until 140 and not beyond that.
Your print method does not work because you decrement the size every time you invoke your dequeue() method in the for loop. If you are going to use a for loop you should be using a fixed size. Basically in this statement ( i < q.size() ) as i grows size decreases. If i = 0 and size = 4 the first loop i would be 1 and size would be 3. Your never going to get to the 0th or 1st element in your queue because by the next loop your already at i = 2 and size = 3.
first you should add a getter for the queue items
public int getElementAt(int index){
return data[index];
}
then you can call the method in the for loop for every index in data
int length = q.size();
for(int i = 0; i < length; i++){
System.out.println(q.getElementAt(i));
}
If it is not mandatory to do an array implementation, I would suggest using the Vector class because it has a better API for a queue. I would also suggest slowly tracing your program every time you have issues and to start with smaller test data sets to make tracing a easier.
public class Queue {
private Vector<String> data ;
Queue(){
data = new Vector();
}
public void enqueue(String item){
data.add(item);
}
public void dequeue(){
data.remove(0);
}
public void printQueueItems(){
int length = data.size();
for(int i = 0; i < length; i++){
System.out.println(data.get(i));
}
}
public static void main(String[] args) {
Queue myQ = new Queue();
myQ.enqueue("hello");
myQ.enqueue("world");
myQ.enqueue("!");
myQ.printQueueItems();
}
}
So I have a class assignment where the class I create implements an interface.
The main goals are to implement a new kind of queue that only accepts a single copy of an object in the queue,If an element is enqueued, and the element already exists in the queue, the queue will remain unchanged, and include a method moveToBack that allows you to de-prioritize an element in the queue.
I have several problems with my class that I am having troubles fixing.
1) there's an issue with my the NoDupes class inheriting from the Queue interface twice but when I try to fix by getting rid of the inheritance in the ArrayQueue class I can't get it to run
2) missing a loop that increments in moveToBack method but when I try fixing same issue as previous problem.
3)foundValue doesn't initialize
4)display(): should not print nulls when the queue is empty.
5) I don't know to implement enqueue().
The following is the classes I am implementing as my attempt, any help would be appreciated:
The ArrayQueue
public class ArrayQueue<T> implements QueueInterface<T> {
private T[] queue; // circular array of queue entries and one unused location
private int frontIndex;
private int backIndex;
private static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayQueue() {
this(DEFAULT_INITIAL_CAPACITY);
}
public ArrayQueue(int initialCapacity) {
queue = (T[]) new Object[initialCapacity + 1];
frontIndex = 0;
backIndex = initialCapacity;
}
public void enqueue(T newEntry) {
if (isArrayFull()) {
doubleArray();
}
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
}
public T getFront() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
}
return front;
}
public T dequeue() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
queue[frontIndex] = null;
frontIndex = (frontIndex + 1) % queue.length;
}
return front;
}
public boolean isEmpty() {
return frontIndex == ((backIndex + 1) % queue.length);
}
public void clear() {
if (!isEmpty()) { // deallocates only the used portion
for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length) {
queue[index] = null;
}
queue[backIndex] = null;
}
frontIndex = 0;
backIndex = queue.length - 1;
}
private boolean isArrayFull() {
return frontIndex == ((backIndex + 2) % queue.length);
}
private void doubleArray() {
T[] oldQueue = queue;
int oldSize = oldQueue.length;
queue = (T[]) new Object[2 * oldSize];
for (int index = 0; index < oldSize - 1; index++) {
queue[index] = oldQueue[frontIndex];
frontIndex = (frontIndex + 1) % oldSize;
}
frontIndex = 0;
backIndex = oldSize - 2;
}
}
public interface NoDupsDePrioritizeQueueInterface <T> extends
QueueInterface<T> {
/*
* Task: Moves the given entry to the back of the queue. If the entry is not
* in the queue, just add it at the end.
*
* #param entry the item to move or add
*/
public void moveToBack(T entry);
/*
* * Task: displays the contents of the queue (to be used for testing);
* specifies the front and back of the queue
*/
public void display();
}
public interface QueueInterface<T> {
public void enqueue(T newEntry);
/**
* Task: Removes and returns the entry at the front of the queue.
*
* #return either the object at the front of the queue or, if the queue is
* empty before the operation, null
*/
public T dequeue();
/**
* Task: Retrieves the entry at the front of the queue.
*
* #return either the object at the front of the queue or, if the queue is
* empty, null
*/
public T getFront();
/**
* Task: Detects whether the queue is empty.
*
* #return true if the queue is empty, or false otherwise
*/
public boolean isEmpty();
/** Task: Removes all entries from the queue. */
public void clear();
} // end QueueInterface
My implementation:
public class NoDupsDePrioritizeQueueInterface<T>
extends ArrayQueue
implements NoDupsDePrioritizeQueue<T> { //note, this was glitched before edit
public NoDupsDePrioritizeQueue() {
super();
}// end NoDupsDePrioritizeQueue
public NoDupsDePrioritizeQueue(int initialCapacity) {
super(initialCapacity)
}// end NoDupsDePrioritizeQueue
public void moveToBack(T newEntry) {
boolean found = false;
int start = frontIndex;
int back = backIndex;
int index = 0;
if (!isEmpty()) {
//searching if newEntry is already present in the queue. If it is present,
note its index. while (start != back) {
if (newEntry.equals(queue[start])) {
found = true;
index = start;
break;
}
start = (start + 1) % queue.length;
}
// the condition does not check queue[back] as the loop exits then.
//Hence we evaluate it separately.
if (newEntry.equals(queue[start])) {
found = true;
index = start;
}
//if its not found in the queue, do normal enqueue
if (found == false) {
enqueue(newEntry);
} else {
//shifting all elemets till the backindex and replacing the last element
//with the newEntry
foundValue = queue[index];
while ((index + 1) % queue.length <= backIndex) {
queue[index] = queue[(index + 1) % queue.length];
}
queue[backIndex] = foundValue;
}
} else {
enqueue(newEntry);
}
}
//end moveToBack
// displaying the queue without destroying it
public void display() {
int start = frontIndex;
int back = backIndex;
while (start != back && !isEmpty()) {
System.out.println(queue[start]);
start = (start + 1) % queue.length;
}
System.out.println(queue[start]);
}
}
The other part
/**
* A class that implements the ADT queue by using an expandable circular
* array
* with one unused location.
*/
public class ArrayQueue<T> {
protected T[] queue; // circular array of queue entries and one unused location
protected int frontIndex;
protected int backIndex;
protected static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayQueue() {
this(DEFAULT_INITIAL_CAPACITY);
}
public ArrayQueue(int initialCapacity) {
queue = (T[]) new Object[initialCapacity + 1];
frontIndex = 0;
backIndex = initialCapacity;
}
public void enqueue(T newEntry) {
//enqueue needs to be changed to eliminate duplicates
if (isArrayFull()) {
doubleArray();
}
boolean found = false;
//if its emtpy array, do normal enqueue operation
if (!isEmpty()) {
int start = frontIndex;
int back = backIndex;
//checking for duplicates by travelling through the array. however, we
//will miss queue[back] as the loop exits then.Hence we will search for it separately.
while (start != back) {
//if found, simply exit
if (newEntry.equals(queue[start])) {
found = true;
System.out.println("Element already exists");
return;
}
start = (start + 1) % queue.length;
}
if (newEntry.equals(queue[start])) {
found = true;
System.out.println("Element already exists");
return;
}
}
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
}
public T getFront() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
}
return front;
}
public T dequeue() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
queue[frontIndex] = null;
frontIndex = (frontIndex + 1) % queue.length;
}
return front;
}
public boolean isEmpty() {
return frontIndex == ((backIndex + 1) % queue.length);
}
public void clear() {
if (!isEmpty()) { // deallocates only the used portion
for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length) {
queue[index] = null;
}
queue[backIndex] = null;
}
frontIndex = 0;
backIndex = queue.length - 1;
}
private boolean isArrayFull() {
return frontIndex == ((backIndex + 2) % queue.length);
}
private void doubleArray() {
T[] oldQueue = queue;
int oldSize = oldQueue.length;
queue = (T[]) new Object[2 * oldSize];
for (int index = 0; index < oldSize - 1; index++) {
queue[index] = oldQueue[frontIndex];
frontIndex = (frontIndex + 1) % oldSize;
}
frontIndex = 0;
backIndex = oldSize - 2;
}
}
For your first question, the class declaration for NoDupsDePrioritizeQueue is just broken. I think you copied and pasted something wrong. Your wording implies that you somehow got this to run, which I completely disbelieve.
public class NoDupsDePrioritizeQueueInterface<T> extends ArrayQueue
NoDupsDePrioritizeQueue<T> implements {
This makes no sense. This is declaring a class which duplicates the name of your interface (which would never compile due to the name collision), has it extend another class and ... the second line is backwards/broken (which, again, would never compile). I think this should probably be
public class NoDupsDePrioritizeQueue<T> extends ArrayQueue
implements NoDupsDePrioritizeQueueInterface<T> {
This declares the class NoDupsDePrioritizeQueue, extending a class and implementing the interface.
I was required to create a simple queue array implementation with basic methods as enqueue, dequeue, isEmpty, and stuff like that. My only problem is that Im stuck when it comes to the resize method, because if I want to add more values to my queue (with fixed size because is an array) I do not know how to make it work and keep all the values in place.
Everything works just in case you were wondering, the only thing is that doesnt work is my resize (the method wrote in here wasn't the only one I tried).
I'm going to put my main method as well if you want to try it, hope you can help, thanks.
Main Method:
public class MainQueue {
public static void main(String[] args) {
int capacity=10;
Queue<Integer> queue = new Queue<Integer>(capacity);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
queue.enqueue(7);
queue.enqueue(8);
queue.enqueue(9);
queue.enqueue(10);
System.out.println("Queue: "+ queue);
//WORKS SO FAR
queue.enqueue(11);
//11 is placed at the beginning of the queue
//instead at the end and my last value is null (?)
Class queue:
import java.util.NoSuchElementException;
public class Queue <E>{
private E[] elements;//array in generic
private int front;//first element or front of the queue
private int back;//last element or back of the queue
private int capacity; //capacity of the queue
private int count; //indicates number of elements currently stored in the queue
#SuppressWarnings("unchecked")
public Queue(int size)
{
capacity = size;
count = 0;
back = size-1;
front = 0;
elements =(E []) new Object[size]; //array empty
}
//Returns true if the queue is empty or false
public boolean isEmpty()
{
return count==0;//means its true
}
//Add elements to the queue
public void enqueue(E item)
{
if(count == capacity)
{
resize(capacity*2);
// System.out.println("Queue is full");
}
back =(back+1) % capacity; //example back=(0+1)%10=1
elements[back]=item;
//elements[0]=0
//item=elements[count];
count++;
}
//Public resize
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
}
//Dequeue method to remove head
public E dequeue()
{
if(isEmpty())
throw new NoSuchElementException("Dequeue: Queue is empty");
else
{
count--;
for(int x = 1; x <= count; x++)
{
elements[x-1] = elements[x];
}
capacity--;
return (E) elements;
}
}
//peek the first element
public E peek()
{
if(isEmpty())
{
throw new NoSuchElementException("Peek: Queue is empty");
}
else
return elements[front];
}
//Print queue as string
public String toString()
{
if(isEmpty()) {
System.out.println("Queue is empty.");
//throw new NoSuchElementException("Queue is empty");
}
String s = "[";
for(int i = 0; i <count; i++)
{
if(i != 0)
s += ", ";
s = s + elements[i];// [value1,value2,....]
}
s +="]";
return s;
}
public void delete() { //Delete everything
count = 0;
}
}
you forgot to update stuff when resizing:
front, capacity and back .
public void resize(int reSize){
E[] tmp = (E[]) new Object[reSize];
int current = front;
for (int i = 0; i < count; i++)
{
tmp[i] = elements[current];
current = (current + 1) % count;
}
elements = tmp;
front = 0;
back = count-1;
capacity=reSize;
}
You have few mistakes in resizing when enqueing item which expand queue.
in resize algorithm
current = (current + 1) % count; should be (current + 1) % capacity
You have to change capacity value in resize function
capacity = resize;
Why are you changing capacity when dequeing?