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?
Related
import java.util.Scanner;
class ed {
int fr, r;
int q[];
int n;
ed(int x) {
n = x;
fr = -1;
r = -1;
q = new int[n];
}
void enque(int n) {
int val = n;
while (r < n-1) {
if (r==n-1) {
System.out.println("Overflow");
break;
}
else if (fr==-1 && r==-1) {
fr=0;
r=0;
q[r] = val;
}
else {
r += 1;
q[r] = val;
}
}
}
void deque() {
if (fr==-1 && r==-1) {
System.out.println("Underflow");
}
else if (fr==r) {
fr=-1;
r=-1;
}
else {
fr += 1;
}
}
void reverse(int[] q) {
int a = q[0];
deque();
reverse(q);
enque(a);
}
void printq() {
for (int i = fr; i<=r; i++) {
System.out.print(q[i] + " ");
}
}
}
public class q1 {
static Scanner f = new Scanner (System.in);
public static void main(String[] args) {
int n = f.nextInt();
ed que = new ed(n);
for (int i=0; i<n; i++) {
int x = f.nextInt();
que.enque(x);
}
// que.deque();
// que.printq();
que.reverse(que.q);
}
}
My aim is to reverse a queue (Array) using a recursive function, but in VS Code, the loop is running infinite times and I'm not getting a chance to see the error. I'd like to know my mistake, and any improvement is highly appreciated.
The class ed contains a constructor which initializes the array and the front, rear values. Enque method adds an element to the queue at the rear, deque method removes the front element. Reverse method takes an array input (queue), stores the foremost element in the variable a, deques it, calls itself, then enques it at the back. VS Code is showing the error at line 48 (reverse(q), when it calls itself) but it's not showing the error as it's so far up.
A lot of things are not going the right way in your queue implementation using arrays.
Like, in enque function, you can fill values from rear = 0 to rear = n - 1, because you have n positions available in the q array.
Your code was too long, unstructured, and a bit messy with no proper variable names, So, I didn't read it any further.
But one thing I can make out is that you need to read how to implement a queue using the array.
Now, coming to queue reversal using the recursion part.
Your approach was correct, you just missed out the base case condition.
Steps for reversing queue:
Your queue has some elements, we get the first element out of the queue.
Then, we assume I have a recursive function that reverses the rest of the queue.
In this reversed queue, I just have to push that first element to the back.
And coming to the base case, each time queue size is decreasing by 1, so at the end, the queue will become empty then we don't have to do anything, just return. THUS STOPPING THE RECURSION (which you missed).
Here, is my implementation if you need some reference:
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class Queue {
private int front, rear, capacity;
private int queue[];
Queue(int c) {
front = rear = 0;
capacity = c;
queue = new int[capacity];
}
int size() {
return rear - front;
}
void enqueue(int data) {
if (capacity == rear) {
System.out.printf("Queue is full.\n");
return;
}
else {
queue[rear] = data;
rear++;
}
}
void dequeue() {
if (front == rear) {
System.out.printf("Queue is empty.\n");
return;
}
else {
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
}
int front() {
if (front == rear) {
System.out.printf("\nQueue is Empty.\n");
return -1;
}
return queue[front];
}
void print() {
int i;
if (front == rear) {
System.out.printf("Queue is Empty.\n");
return;
}
for (i = front; i < rear; i++) {
System.out.printf(" %d, ", queue[i]);
}
System.out.println("");
return;
}
}
class GFG {
static Scanner scanner = new Scanner(System.in);
public static void reverseQueue(Queue queue) {
if (queue.size() == 0) {
return;
}
int frontElement = queue.front();
queue.dequeue();
reverseQueue(queue);
queue.enqueue(frontElement);
}
public static void main (String[] args) {
int queueSize = scanner.nextInt();
Queue queue = new Queue(queueSize);
for (int i = 0; i < queueSize; i++) {
int element = scanner.nextInt();
queue.enqueue(element);
}
queue.print();
reverseQueue(queue);
queue.print();
}
}
You can comment if anything is wrong, or need more clarification.
I working on my homework assignment, build code to queue with support of interface, I wrote my code but the output hade main.thread issue, to be honest I could not find the issue,however I do believe the issue is from insertion,mainly in the size increment, I appreciate some advice
public class MyQueue implements IntQueue {
private int[] heltal;
private int size;
public void enqueue(int tal) {
// Inserts the specified element into the end of this queue.
// increases the size after every insertion
if (size == 0) {
size++;
heltal[0] = tal;
int[] newArr = new int[heltal.length * 2];
for (int i = 0; i < heltal.length; i++) {
newArr[i] = heltal[i];
}
heltal = newArr;
}
return;
}
public int dequeue() throws NoSuchElementException {
// Returns the head of this queue and removes it.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
int NewValue = heltal[0];
for (int i = 1; i < size; i++) {
heltal[i - 1] = heltal[i];
}
heltal[size - 1] = 0;
size--;
return NewValue;
}
#Override
public int peek() throws NoSuchElementException {
// Retrieves, but does not remove, the head of this queue.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
return heltal[0];
}
#Override
public boolean empty() {
// Checks if this queue is empty.
return size == 0;
}
}
Initialize your array like below
private int[] heltal = new int[100];
and see if it works
I am trying to print the elements of stack S in reverse (using a "for" loop), but so far I haven't had any success.
I have managed to do it with "pop" fairly easily, but the second way evades me. My solution for "pop" is commented out at the end of the code.
Any help will be appreciated.
PS. Most of this code is irrelevant to the question, but if I knew what and where I can cut out, I probably wouldn't need help at all. Sorry.
package simplearraystackofchars;
public class SimpleArrayStackofchars implements Stack {
protected int capacity; // The actual capacity of the stack array
public static final int CAPACITY = 2; // default array capacity
protected Object S[], K[]; // Generic array used to implement the stack
protected int top = -1; // index for the top of the stack (-1 = empty stack)
public SimpleArrayStackofchars() {
this(CAPACITY); // default capacity
}
public SimpleArrayStackofchars(int cap) {
capacity = cap;
S = new Object[capacity];
}
public int size() {
return (top + 1);
}
public boolean isEmpty() {
return (top == -1);
}
public void push(Object element) throws FullStackException {
if (size() == capacity) {
//throw new FullStackException("Stack is full. Stack size max is "+ capacity);
// can replace previous line with code to double stack size
doubleArray();
}
S[++top] = element;
}
public Object top() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
return S[top];
}
public Object pop() throws EmptyStackException {
Object element;
if (isEmpty()) {
throw new EmptyStackException("Stack is empty.");
}
element = S[top];
S[top--] = null; // dereference S[top] for garbage collection.
return element;
}
private void doubleArray() {
Object[] newArray;
System.out.println("Stack is full (max size was " + capacity + "). Increasing to " + (2 * capacity));
//double variable capacity
capacity = 2 * capacity;
newArray = new Object[capacity];
for (int i = 0; i < S.length; i++) {
newArray[i] = S[i];
}
S = newArray;
}
public static void main(String[] args) {
Stack S = new SimpleArrayStackofchars();
S.push("1");
S.push("2");
S.push("3");
S.push("4");
S.push("5");
S.push("6");
// Stack K is created by popping elements of Stack S from the top.
// This reverses the order.
//
// Stack K = new SimpleArrayStackofchars();
// while (!S.isEmpty()) {
// K.push(S.pop());
// }
// while (!K.isEmpty()) {
// System.out.println(K.pop());
// }
while (!S.isEmpty()) {
System.out.println(S.pop());
}
}
}
Not really sure about what you need that for loop for, but this should produce the same result:
Stack K = new SimpleArrayStackofchars();
for (int i = 0, i < S.size(); i++) {
K.push(S.pop());
}
for (int i = 0, i < K.size(); i++) {
System.out.println(K.pop());
}
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 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);
}
}