I have to make a program in Java that includes an array of queues created from my queue class that I have made which is as follows -
class Queue1{ //each line at the supermarket
public Queue1(int s){ //constructor
maxSize = s;
pplLines = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(long j){ //put item at rear of queue
if(rear == maxSize - 1) //deal with wraparound
rear = -1;
pplLines[++rear] = j; //increment rear and insert
nItems++; //one more item
}
public long remove(){ //take item from front of queue
long temp = pplLines[front++]; //get value and increment front
if(front == maxSize) //deal with wraparound
front = 0;
nItems--; //one less item
return temp;
}
public long peekFront(){ //peek at front of queue
return pplLines[front];
}
public boolean isEmpty(){ //true if queue is empty
return (nItems == 0);
}
public boolean isFull(){ //true if queue is full
return (nItems == maxSize);
}
public int size(){ //number of items in queue
return nItems;
}
public void display(){ //display contents of queue
for (int i = 0; i < nItems; i++) {
System.out.println(pplLines[(front + i) % maxSize]);
}
}
}//ends queue class
So how can I reference the queue class into an array starting with this
public SuperMarket(int num_clerks, int line_size){
After that I have the array of queues created I need to find the shortest line to insert a customer where I have to input the number of clerks/lines available at the supermarket, how would I go about adding that to my SuperMarket class?
Thanks for the help!
if you do something like
public SuperMarket(int num_clerks, int line_size){
List<Queue1> clerks = new ArrayList<Queue1>();
for(int i; i< num_clerks; i++){
clerks.add(new Queue1(line_size))
}
}
Related
I have the following code where I have implemented a circular array. The problem comes when I try to display it. The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute.
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated! Thank You
You can change the loop so it iterates from 0 to size. This also fixes the problem where last is less than first because items have been removed.
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}
Just use the properties on the array itself to display:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}
When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.
I've been trying to double the size of my queue and I have tried several different methods, this one has given me the closest result to what I am trying to get, however, it copies all the values already in the queue into the newly created spaces instead of leaving them empty for me to add more objects.
I have two classes, and the only part I need to change is the enqueue method.
The last line should print 50 40 30 20 60 70 instead.
public class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count ==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
} else
System.out.println("Queue is full. Doubling the size.");
count = (QUEUE_SIZE*2);
System.out.println("New max size is: " + QUEUE_SIZE);
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println("Trying to dequeue from empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println("Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
import java.util.Stack;
public class Runner {
public static void main(String[] args) {
Queue q = new Queue();
createQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to dequque one element.");
q.dequeue();
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to reverse my queue: ");
reverseQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 60.");
q.enqueue(60);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 70.");
q.enqueue(70);
System.out.println("My queue is as follows: ");
printQueue(q);
}
public static Queue createQueue(Queue q){
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
return q;
}
public static void printQueue(Queue q){
int s = q.size();
for(int i=0; i<s; i++){
int temp = (int)q.dequeue();
q.enqueue(temp);
System.out.print(temp+ " ");
}
System.out.println();
}
public static void reverseQueue(Queue q){
Stack s = new Stack();
while(!q.isEmpty()){
s.push(q.dequeue());
}while(!s.isEmpty()){
q.enqueue(s.pop());
}
}
}
The else block in enqueue(Object newItem) does not insert new Object so it should be like this :
public void enqueue(Object newItem) {
if (!isFull()) {
back = (back + 1) % QUEUE_SIZE;
items[back] = newItem;
count++;
return;
}
else {
System.out.println("Queue is full. Doubling the size.");
QUEUE_SIZE = (QUEUE_SIZE * 2); // double queue size not count
System.out.println("New max size is: " + QUEUE_SIZE);
Object[] temp = new Object[QUEUE_SIZE]; // temp array
System.arraycopy(items, front, temp, front, items.length - front); // copy the elements from front index to items.length-front
if (front != 0) {
System.arraycopy(items, 0, temp, items.length, front); // copy the elements in the range items[0] to items[back] into the new array
}
items = temp; // set items to temp array
back = front + count;
items[back] = newItem; // set new item
count++; // increment count
}
}
It is about printQueue() method, after the count = (QUEUE_SIZE*2); line of enqueue() method the size of items array actually didn't expand. It is still 5 in any case, count = (QUEUE_SIZE*2); provide that isFull() method returns false.
If you debug printQueue() method, you will see that int s = 10 but items array still [30, 20, 60, 50, 40].
After Queue becomes full, You are not enqueuing the items. So the item is not inserted into the queue after becomes full.Have modified the code.
package org.sunil.addressbook.dao;
import java.util.Stack;
class Queue{
private int QUEUE_SIZE = 5;
private Object[] items;
private int front, back, count;
public Queue() {
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public boolean isEmpty(){
return count ==0;
}
public boolean isFull(){
return count == QUEUE_SIZE;
}
public void enqueue(Object newItem){
if (!isFull()){
back = (back+1) % QUEUE_SIZE;
// System.out.println("back output is "+back);
items[back] = newItem;
count++;
} else{
System.out.println("Queue is full. Doubling the size.");
back=QUEUE_SIZE-1;
QUEUE_SIZE = (QUEUE_SIZE*2);
Object[] temp = new Object[QUEUE_SIZE];
int j=0;
for (int i = front; i < items.length; i++){
temp[j] = items[i];
j++;
}
for (int i = 0; i < front; i++){
temp[j] = items[i];
j++;
}
items = temp;
front=0;
back = (back+1) % QUEUE_SIZE;
items[back] = newItem;
count++;
}
}
public Object dequeue(){
if (!isEmpty()){
Object queueFront = items[front];
front = (front+1) % QUEUE_SIZE;
count--;
return queueFront;
}else
System.out.println("Trying to dequeue from empty queue");
return null;
}
public void dequeueAll(){
items = new Object[QUEUE_SIZE];
front = 0;
back = QUEUE_SIZE -1;
count =0;
}
public Object peek(){
if (!isEmpty()) {
return items[front];
}
else
System.out.println("Trying to peek with empty queue");
return null;
}
public int size(){
return count;
}
}
public class Runner {
public static void main(String[] args) {
Queue q = new Queue();
createQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to dequque one element.");
q.dequeue();
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to reverse my queue: ");
reverseQueue(q);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 60.");
q.enqueue(60);
System.out.println("My queue is as follows: ");
printQueue(q);
System.out.println("I am going to enqueue 70.");
q.enqueue(70);
System.out.println("My queue is as follows: ");
printQueue(q);
}
public static Queue createQueue(Queue q){
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
return q;
}
public static void printQueue(Queue q){
int s = q.size();
for(int i=0; i<s; i++){
int temp = (Integer)q.dequeue();
q.enqueue(temp);
System.out.print(temp+ " ");
}
System.out.println();
}
public static void reverseQueue(Queue q){
Stack s = new Stack();
while(!q.isEmpty()){
s.push(q.dequeue());
}while(!s.isEmpty()){
q.enqueue(s.pop());
}
}
}
I have the java code and been able to come up with a toString as shown below in the code:
public class CircularArrayQueue<T> implements QueueADT<T>
{
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private T[] queue;
//-----------------------------------------------------------------
// Creates an empty queue using the default capacity.
//-----------------------------------------------------------------
public CircularArrayQueue()
{
front = rear = count = 0;
queue = (T[]) (new Object[DEFAULT_CAPACITY]);
}
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public CircularArrayQueue (int initialCapacity)
{
front = rear = count = 0;
queue = ( (T[])(new Object[initialCapacity]) );
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enqueue (T element)
{
if (size() == queue.length)
expandCapacity();
queue[rear] = element;
rear = (rear+1) % queue.length;
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 T dequeue() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("queue");
T result = queue[front];
queue[front] = null;
front = (front+1) % queue.length;
count--;
return result;
}
//-----------------------------------------------------------------
// Returns a reference to the element at the front of the queue.
// The element is not removed from the queue. Throws an
// EmptyCollectionException if the queue is empty.
//-----------------------------------------------------------------
public T first() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("queue");
return queue[front];
}
//-----------------------------------------------------------------
// 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;
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
public String toString()
{
String result = "";
int scan = 0;
while(scan < count)
{
if(queue[scan]!=null)
{
result += queue[scan].toString()+"\n";
}
scan++;
}
return result;
}
//-----------------------------------------------------------------
// Creates a new array to store the contents of the queue with
// twice the capacity of the old one.
//-----------------------------------------------------------------
public void expandCapacity()
{
T[] larger = (T[])(new Object[queue.length *2]);
for(int scan=0; scan < count; scan++)
{
larger[scan] = queue[front];
front=(front+1) % queue.length;
}
front = 0;
rear = count;
queue = larger;
}
}
How can I modify my toString based on these output for my queue:
I want to Start with an initial String showing the number of cars
If the queue is empty, thenI will return the initial String.
If front is at, or ahead of, back
I want to add a line for each car from front to the end
then add lines for those from the start of the array to back-1
else I want to add a line for each car between front and back-1.
This is my current toString() :
public String toString()
{
String result = "";
for (int scan=0; scan < rear; scan++)
result = result + queue[scan].toString() + "\n";
return result;
}
You wrote the pseudo-code, a few if/else-if blocks do the rest.
public String toString()
{
String result = String.format("There are %d items in the queue.", count);
if (count == 0)
{
return result;
}
else if (front >= back)
{
for (int i = front; i < count; i++)
{
result += queue[i].toString() + "\n";
}
for (int i = 0; i < back; i++)
{
result += queue[i].toString() + "\n";
}
}
else
{
for (int i = front; i < back; i++)
{
result += queue[i].toString() + "\n";
}
}
return result;
}
So I was required to do an implementation of queue in arrays, and I wasn't having any trouble till I saw I was getting a funny output after I dequeue and try to enqueue another value...
For example (output):
Queue: [1] //Enqueue 1
Queue: [1, 2] //Enqueue 2
Queue: [2] //Dequeue
Queue: [2, 2] //Enqueue 3
Queue: [2, 2, 3] //Enqueue 4
Queue: [5, 2, 3, 4] //Now is a total mess...
My code contains queue, dequeque and resize methods everything was working fine and I really don't have any idea at all of how to fix it anymore...
Here's my code with the main if you want to try it. Thanks.
public class MainQueue {
public static void main(String[] args) {
int capacity=5;
Queue<Integer> queue = new Queue<Integer>(capacity);
queue.enqueue(1);
System.out.println("Queue: "+ queue);
queue.enqueue(2);
System.out.println("Queue: "+ queue);
queue.dequeue();
queue.enqueue(3);
System.out.println("Queue: "+ queue);
queue.enqueue(4);
System.out.println("Queue: "+ queue);
queue.enqueue(5);
System.out.println("Queue: "+ queue);
}
}
Class
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
public Queue(int size)
{
capacity = size;
count = 0;
back = size-1;
front = 0;
elements =(E []) new Object[size]; //queue 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;
front = 0;
back = count-1;
capacity=reSize;
}
//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()) {
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 are updating the back in the enqueue() method using the current value of back, but you aren't updating it in the dequeu() method at all. That is not going to work correctly. In fact, you should rather calculate back based on count.
Just change:
back = (back + 1) % capacity;
to:
back = count % capacity;
In dequeue you are not updating the back variable that determines the position on which you add new value with enqueue. Furthermore in dequque you could copy nonexistent value on index 0 from index 1 when you have count just of 1. This is a special case that will make out of bounds error if you made a queue with capacity(size) of 1, enqueued something and then dequeued it.