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.
Related
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;
}
}
I have a method which I basically want to simulate first filling the queue and then after that removing the first person and adding a new person each time in my public void mySimulation() method:
import java.util.*;
public class People {
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private ArrayList<thePeople> people;
private int theMaxCapacity;
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public People(int initialCapacity) {
front = rear = count = 0;
people = new ArrayList<thePeople>(Collections.nCopies(5, (thePeople) null));
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enque(thePeople element) {
if (this.isFull()) {
System.out.println("Queue Full");
System.exit(1);
} else {
people.set(rear, element);
rear = rear + 1;
if (rear == people.size()) {
rear = 0;
}
count++;
}
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public thePeople dequeue() {
if (isEmpty()) {
System.out.println("Empty Queue");
}
thePeople result = people.get(front);
people.set(front, null);
front = (front + 1) % people.size();
count--;
return result;
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty() {
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size() {
return count;
}
public boolean isFull() {
return count == people.size();
}
public void mySimulation() {
Random rand1 = new Random();
thePeople theM = null;
if (this.isFull()) {
this.people.remove(0);
System.out.println("Enqueueing...");
this.enque(people.get(rand1.nextInt(people.size())));
thePeople r1 = people.get(rear - 1);
System.out.println(people.toString());
System.out.println(r1);
for (int e = 0; e < people.size(); e++) {
if (people.get(e) instanceof thePeople) {
System.out.println("G");
} else {
System.out.println("D");
}
}
}
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
#Override
public String toString() {
String result = "";
int scan = 0;
while (scan < count) {
if (people.get(scan) != null) {
result += people.get(scan).toString() + "\n";
}
scan++;
}
return result;
}
public static void main(String[] args) {
People Q1 = new People(25);
thePeople call1 = new thePeople("John King", "001 456 789");
thePeople call2 = new thePeople("Michael Fish", "789 654 321");
Q1.enque(call1);
Q1.enque(call2);
System.out.println(Q1.toString());
ArrayList<thePeople> callerDetails = new ArrayList<>(Arrays.asList(call1, call2));
Random rand = new Random();
for (int z = 0; z <= 4; z++) {
Q1.enque(callerDetails.get(rand.nextInt(callerDetails.size())));
}
System.out.println(Q1.toString());
}
}
any suggestions on how I could repeat this process such that I will first check that the queue is full,
if so remove the first item and add a new person to it using my arrayList each time i my my public void mySimulation() method: as I cant get my head round this at the moment?
Your code is filled with errors:
First make sure you remove the "the" you accidently placed before people in many lines of your code .
Then adjust some of your methods to the right parameters and return types.
As for you question:
it is simple
public void MySimulation(){
if(Queue.isFull()){
Queue.dequeue;}
Queue.enqueue;}
I am trying to implement PatriciaTrie data structure. I was recently asked this question in a coding interview through Google Docs. But I was not able to answer this.
I made some progress by adding insert method in the below code but got stuck on the remove method in the PatriciaTrie code - not sure how to implement that -
Below is my PatriciaTrie code -
public class PatriciaTrie {
protected static class Edge {
Node target;
TTString label;
public Edge(Node target, TTString label) {
this.target = target;
this.label = label;
}
}
protected static class Node {
Edge[] edges; // the children of this node
int numberOfChildren; // the number of children
public Node() {
edges = new Edge[128];
numberOfChildren = 0;
}
}
/**
* number of strings stored in the trie
*/
protected int number;
/**
* This is root
*/
protected Node root;
public PatriciaTrie() {
root = new Node();
number = 0;
}
/**
* Add the x to this trie
* #param x the string to add
* #return true if x was successfully added or false if x is already in the trie
*/
public boolean insert(TTString x) {
Node current = root;
for (int i = 0; i < x.length(); i++) {
TTString ch = x.subString(i, 1);
if (current.edges[x.charAt(i)] != null) {
Node child = current.edges[x.charAt(i)].target;
current = child;
} else {
current.edges[x.charAt(i)] = new Edge(new Node(), ch);
current.numberOfChildren++;
current = current.edges[x.charAt(i)].target;
}
if (i == x.length() - 1)
return true;
}
return false;
}
/**
* Remove x from this trie
* #param x the string to remove
* #return true if x was successfully removed or false if x is not stored in the trie
*/
public boolean remove(TTString x) {
// not sure how to do this
return false;
}
}
And below is my TTString class -
public class TTString {
int i; // index of first character
int m; // length
byte[] data; // data
public TTString(String s) {
data = s.getBytes();
i = 0;
m = s.length();
}
protected TTString(byte[] data, int i, int m) {
this.data = data;
this.i = i;
this.m = m;
}
public TTString subString(int j, int n) {
if (j < 0 || j >= m) throw new IndexOutOfBoundsException();
if (n < 0 || j + n > m) throw new IndexOutOfBoundsException();
return new TTString(data, i+j, n);
}
/**
* The length of this string
* #return
*/
public int length() {
return m;
}
/**
* Return the character at index j
* #param j
* #return
*/
public char charAt(int j) {
return (char)data[i+j];
}
}
Any thoughts on how to implement remove method here?
One idea is: descend from the root to the leaf corresponding to the last character of x (assuming there is path containing x, otherwise there's nothing to change), remembering last fork on your path in the process (first fork is at the root). When you at the leaf, remove all edges/nodes from the last fork till the leaf.
I have implemented it in C# on TRIE data structure for the string code is follow. You can see the complete code here http://devesh4blog.wordpress.com/2013/11/16/real-time-auto-complete-using-trie-in-c/
public void RemoveWord(string word, TRIENode rootNode, string id)
{
int len = word.Length;
if (len == 0)
{
rootNode.PrefixCount--;
if (rootNode.PrefixCount == 0)
rootNode.IsCompleteWord = false;
rootNode.Ids.Remove(id);
return;
}
for (int i = 0; i < len; i++)
{
string key = word.Substring(i, 1);
string lowerVersionKey = key.ToLower();
rootNode.PrefixCount--;
rootNode = rootNode.Children[lowerVersionKey];
}
rootNode.Ids.Remove(id);
if (rootNode.Ids.Count == 0)
rootNode.IsCompleteWord = false;
}
This is my code and sample tests:
protected static class Edge {
Node target;
TTString label;
public Edge(Node target, TTString label) {
this.target = target;
this.label = label;
}
}
protected static class Node {
Edge[] edges; // the children of this node
int numberOfChildren; // the number of children
// isEnd is true means this node is a string's end node.
boolean isEnd;
public Node() {
edges = new Edge[128];
numberOfChildren = 0;
isEnd = false;
}
}
/**
* number of strings stored in the trie
*/
protected int number;
/**
* This is root
*/
protected Node root;
public PatriciaTrie() {
root = new Node();
number = 0;
}
/**
* Add the x to this trie
*
* #param x
* the string to add
* #return true if x was successfully added or false if x is already in the
* trie
*/
public boolean insert(TTString x) {
// not sure what I am supposed to do here?
Node current = root;
for (int i = 0; i < x.length(); i++) {
TTString ch = x.subString(i, 1);
if (current.edges[x.charAt(i)] != null) {
Node child = current.edges[x.charAt(i)].target;
current = child;
} else {
current.edges[x.charAt(i)] = new Edge(new Node(), ch);
current.numberOfChildren++;
current = current.edges[x.charAt(i)].target;
}
if (i == x.length() - 1) {
// mark this node is the string x's end node.
current.isEnd = true;
return true;
}
}
return false;
}
// find the string x in the trie, if true, return the x.
public TTString find(TTString x) {
boolean isOk = false;
Node current = root;
for (int i = 0; i < x.length(); i++) {
if (current.edges[x.charAt(i)] != null) {
current = current.edges[x.charAt(i)].target;
} else {
isOk = false;
}
if (i == x.length() - 1 && current.isEnd == true) {
isOk = true;
}
}
if (isOk == false)
return null;
else
return x;
}
public boolean remove(TTString x) {
Node current = root;
for (int i = 0; i < x.length(); i++) {
if (current.edges[x.charAt(i)] != null) {
current = current.edges[x.charAt(i)].target;
} else {
return false;
}
if (i == x.length() - 1) {
// delete the string x.
current.isEnd = false;
return true;
}
}
return false;
}
void run() {
/*
* Here is the sample patricialTrie whose edges are labeled with
* letters.
*/
TTString tmp = new TTString("ABCD");
System.out.println(insert(tmp) ? "YES" : "NO");
Node current = root;
for (int i = 0; i < tmp.length(); i++) {
System.out.println(current.edges[tmp.charAt(i)].label.charAt(0));
current = current.edges[tmp.charAt(i)].target;
}
tmp = new TTString("ABCDE");
insert(tmp);
tmp = new TTString("ABDF");
insert(tmp);
/*
* remove method
*/
tmp = new TTString("ABCDE");
System.out.println(remove(tmp) ? "YES" : "NO");
System.out.println(find(tmp) == null ? "NULL" : find(tmp));
tmp = new TTString("ABCD");
System.out.println(find(tmp) == null ? "NULL" : find(tmp));
}
public static void main(String args[]) {
new PatriciaTrie().run();
}
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?
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);
}
}