Circular queue array implementation - java

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

I'd recommend you to check if front>=0 in deteleArr function. Also you should use the queue instance defined in main, and not a new instance:
void deleteArr(String task[]) {
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
if(front>=0) {
task[NUM]=Integer.toString(items[front]);
}
this.deQueue();
}
If you want, you can use the following display queue function:
void display() {
int i;
System.out.println("Print queue");
System.out.println("===========");
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
for (i = front; i <= rear; i++) {
System.out.println("item["+i+"]: " +items[i]);
}
System.out.println("Rear -> " + rear);
}
System.out.println("============");
}
And you can use this another function to display the task array:
public static void printTaskArray(String task[]) {
System.out.println("Print task[]");
System.out.println("============");
if (task.length==0) {
System.out.println("Empty task");
} else {
for (int j = 0; j < task.length; j++) {
System.out.println("task["+j+"]: "+task[j]);
}
}
System.out.println("============");
}
With this encapsulation you can change your main as follows:
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue ();
q.initialize(task);
printTaskArray(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
printTaskArray(task);
q.display();
while (true) {
q.deleteArr(task);
printTaskArray(task);
q.display();
}
}
I hope this help you.

Related

BubbleDown function(min heap) not working

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.

How does one replace last element of full stack with new element? (java)

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);
}

My code is not printing all the elements of the queue. What is the error?

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();
}
}

How do you implement Comparable in this situation?

I've looked up examples as to how Comparable works and I somewhat understand how it would work but I don't know how I would use it in this situation.
I have an ArrayObject class implements Comparable and imported java.util.*; I also have an ArrayObjectDriver class that is a main method that calls upon methods I've coded in the ArrayObject class. One of the methods that it has to be able to do is to sort the array of objects in the main method. I know you have to use something with .compareTo but I'm not sure how I would do that in the ArrayObject class and call on it in the driver.
EDIT: ArrayObject code
public class ArrayObject implements Comparable
{
private Object[] arr;
private int actualSize;
ArrayObject()
{
arr = new Object[10];
actualSize = 0;
}
ArrayObject(int size)
{
arr = new Object[size];
actualSize = 0;
}
public void add(Object obj)
{
if(actualSize>=arr.length)
expandArray();
arr[actualSize]=obj;
actualSize++;
}
public void expandArray()
{
int newSize = arr.length*2;
Object[] biggerList = new Object[newSize];
for(int i=0; i<arr.length; i++)
{
biggerList[i] = arr[i];
}
arr = biggerList;
}
public void add(Object obj, int index)
{
if(index<actualSize)
{
shiftRight(index);
arr[index]=obj;
actualSize++;
}
// index is between [0 and actualSize)
}
private void shiftRight(int start)
{
for(int i=actualSize; i>start; i--)
{
arr[i] = arr[i-1];
}
arr[start]=null;
}
private void shiftLeft(int start)
{
for(int i=start; i<actualSize-1; i++)
{
arr[i] = arr[i+1];
}
arr[actualSize-1]=null;
}
public Object remove(int index)
{ // returning the object you are removing
// ("the", "is", "are")
if(index>=0&&index<actualSize)
{
Object obj = arr[index];
arr[index] = null;
// arr[index] = arr[actualSize-1];
// what to do about the null?
// Shift to the left by one
shiftLeft(index);
actualSize--;
// ("the", null, "are")
return obj;
}
return null;
}
public Object get(int index)
{
if(index>=0&&index<actualSize)
return arr[index];
return null;
}
public int sizeOfContainer()
{
return arr.length;
}
public int items()
{
return actualSize;
}
public boolean searchArray(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return true;
}
return false;
}
public int findObject(Object obj)
{
if(searchArray(obj))
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return i;
}
}
return -1;
}
public boolean isItEmpty()
{
if(actualSize == 0)
return true;
return false;
}
public int removeSearch(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
{
remove(i);
return i;
}
}
return -1;
}
public void clearArray()
{
for(int i=0; i<actualSize; i++)
arr[i] = remove(i);
}
public void printArr()
{
System.out.println("Array Size: " + actualSize);
for(int i=0; i<actualSize; i++)
{
System.out.println(arr[i]);
}
}
}
ArrayObjectDriver code
public class ArrayObjectDriver
{
private static Scanner scanner;
public static void main(String[] args)
{
scanner = new Scanner(System.in);
ArrayObject array = new ArrayObject();
int selection = selectionMenu();
while(selection > 0)
{
if(selection == 1)
{
System.out.println("Enter your object: ");
String str = scanner.next();
array.add(str);
}
else if(selection == 2)
{
System.out.println("Enter your object: ");
String str = scanner.next();
System.out.println("Enter location: ");
int n = scanner.nextInt();
array.add(str, n);
}
else if(selection == 3)
{
System.out.println("Enter location: ");
int n1 = scanner.nextInt();
array.remove(n1);
}
else if(selection == 4)
{
System.out.println("Enter object: ");
String str = scanner.next();
int i = array.removeSearch(str);
System.out.println("Object removed at index " + i);
}
else if(selection == 5)
{
array.clearArray();
System.out.println("Cleared Array");
}
else if(selection == 6)
{
System.out.println("Enter object: ");
String str = scanner.next();
boolean result = array.searchArray(str);
System.out.println("The object was found: " + result);
}
else if(selection == 7)
{
boolean result = array.isItEmpty();
System.out.println("It is empty: + result);
}
else if(selection == 8)
{
array.expandArray();
int i = array.sizeOfContainer();
System.out.println("The new size of the array is: " + i);
}
else if(selection == 9)
{
System.out.println("Enter object: ")
String str = scanner.next();
int i = array.findObject(str);
System.out.println("The object was found at index " + i);
}
else if(selection == 10)
array.printArr();
else if(selection == 11)
{
}
else if(selection == 12)
System.exit(0);
System.out.println("");
selection = selectionMenu();
}
}
private static int selectionMenu()
{
System.out.println("Menu: ");
System.out.println("1. Add object to the end of the list");
System.out.println("2. Add object at a specific location");
System.out.println("3. Remove specific object at a location");
System.out.println("4. Remove specific object that matches name");
System.out.println("5. Empty the array");
System.out.println("6. See if the array contains a certain object");
System.out.println("7. See if the array is empty");
System.out.println("8. Expand your array");
System.out.println("9. Search for an item");
System.out.println("10. Print array");
System.out.println("11. Sort array");
System.out.println("12. Exit");
System.out.println("Enter option: ");
int optionNumber = scanner.nextInt();
return optionNumber;
}
}
Just make a sort method in your ArrayObject class and you can call that when user enters 11.
In ArraysObject:
public void sort(){
Arrays.sort(arr); //This is all you have to call to sort your array arr
}
In your ArrayObjectDriver:
else if(selection == 11)
{
array.sort();
}
The Arrays class has useful methods for searching, manipulating, and sorting arrays including Arrays.sort and Arrays.binarySearch.

Problem in implementing Sorted List by Array in Java

There seems to be a problem in add method of the class I have written.. I want to make a SortedList using an array, but I can't figure out what the problem is. This is my code:
public class SortedList {
private Integer[] elements;
private int size;
private int capacity;
public SortedList(int cap) {
elements = new Integer[cap];
if (cap > 0)
{
cap = capacity;
}
else
capacity = 10;
}
public boolean isEmpty()
{
return size == 0;
}
public boolean isFull()
{
return size == capacity;
}
public int size()
{
return size;
}
public void doubleCapacity()
{
capacity = capacity * 2;
}
public void add(Integer el)
{
if(this.isEmpty())
{
elements[0] = el;
size++;
}
else if(this.isFull())
{
this.doubleCapacity();
for(int i = 0; i<this.size(); i++)
{
if(el >= elements[i])
{
elements[i+2] = elements[i+1];
elements[i+1] = el;
}
else
{
elements[i+1] = elements[i];
elements[i] = el;
}
}
size++;
}
else
{
for(int i = 0; i<this.size(); i++)
{
if(el >= elements[i])
{
elements[i+2] = elements[i+1];
elements[i+1] = el;
}
else
{
elements[i+1] = elements[i];
elements[i] = el;
}
}
size++;
}
}
public String toString()
{
String s = "";
s = s + "<SortedList[";
for(int i = 0; i < this.size(); i++)
{
s = s + elements[i];
if(i < this.size()-1)
s = s + ",";
}
s = s + "]>";
return s;
}
public static void main(String[] args)
{
SortedList sl = new SortedList(5);
sl.add(3);
//sl.add(2);
sl.add(4);
sl.add(5);
// sl.add(6);
System.out.println(sl.toString());
}
}
My code works if I only add 2 Integers to my list, but when I try to add the numbers 3,4,5 then I get 3,5,5...
What can be the problem? Thanks..
public class SortedList {
private Integer[] elements;
private int size=0;
private int capacity;
public SortedList(int cap) {
elements = new Integer[cap];
if (cap > 0)
{
capacity = cap;
}
else
capacity = 10;
}
public boolean isEmpty()
{
return size == 0;
}
public boolean isFull()
{
return size == capacity;
}
public int size()
{
return size;
}
public void doubleCapacity()
{
capacity = capacity * 2;
}
public void add(Integer el) throws Exception{
elements[size] = el;
size++;
if(size>capacity){
throw new Exception("Size Exceeded");
}
}
public String toString()
{
sort();
String s = "";
s = s + "<SortedList[";
for(int i = 0; i < this.size(); i++)
{
s = s + elements[i];
if(i < this.size()-1)
s = s + ",";
}
s = s + "]>";
return s;
}
public void sort(){
for (int i=0; i <size()-1; i++) {
if (elements[i] > elements[i+1]) {
// exchange elements
int temp = elements[i];
elements[i] = elements[i+1];
elements[i+1] = temp;
}
}
}
public static void main(String[] args)
{
try {
SortedList sl = new SortedList(5);
sl.add(3);
//sl.add(2);
sl.add(6);
sl.add(5);
// sl.add(6);
System.out.println(sl.toString());
} catch (Exception ex) {
Logger.getLogger(SortedList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Your insertion code doesn't work.
elements[i+1] = elements[i];
elements[i] = el;
What happens to the old value of elements[i+1]?
I'd recommend the following changes to the previous solution. If you're only calling sort in toString(), your list is going to get out of order quickly in cases where you have multiple unsorted elements in a row (Now you could remove sort() from toString()). It's essentially a quick insertion sort that dies as soon as it can't make any more swaps down the list. Again, as dty suggested, a faster choice would be a binary search to find the insertion point.
public void doubleCapacity(){
capacity = capacity * 2;
Integer temp[] = new Integer[capacity];
for (int i = 0; i < size; i++){
temp[i] = elements[i];
}
elements = temp;
}
public void add(Integer el){
if(size+1>capacity){
doubleCapacity();
}
elements[size] = el;
size++;
sort();
}
public void sort(){
//Iterates down the list until it's sorted.
for (int i=size()-2; i >= 0 && (elements[i] < elements[i+1]); i--) {
// exchange elements
int temp = elements[i];
elements[i] = elements[i+1];
elements[i+1] = temp;
}
}

Categories

Resources