I was solving a small assignment from the Infytq Learning program, where I come across this hindrance. i can't seem to figure out the problem I'm having.
Given a queue.
I have to form a new queue of whole numbers from the given queue where the numbers in the queue are evenly
divisible by all the numbers from 1 to 10.
Here's what I have done so far. I'm currently getting empty queue.
class Queue {
private int front;
private int rear;
private int maxSize;
private int arr[];
Queue(int maxSize) {
this.front = 0;
this.rear = -1;
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
}
public boolean isFull() {
if (rear == maxSize - 1) {
return true;
}
return false;
}
public boolean enqueue(int data) {
if (isFull()) {
return false;
} else {
arr[++rear] = data;
return true;
}
}
public void display() {
if(isEmpty())
System.out.println("Queue is empty!");
else {
for (int index = front; index <= rear; index++) {
System.out.println(arr[index]);
}
}
}
public boolean isEmpty() {
if (front > rear)
return true;
return false;
}
public int dequeue() {
if (isEmpty()) {
return Integer.MIN_VALUE;
} else {
int data = arr[this.front];
arr[front++] = Integer.MIN_VALUE;
return data;
}
}
public int getMaxSize() {
return maxSize;
}
}
class Tester {
public static void main(String[] args) {
Queue queue = new Queue(7);
queue.enqueue(13983);
queue.enqueue(10080);
queue.enqueue(7113);
queue.enqueue(2520);
queue.enqueue(2500);
Queue outputQueue = findEvenlyDivisibleNumbers(queue);
System.out.println("Evenly divisible numbers");
outputQueue.display();
}
public static Queue findEvenlyDivisibleNumbers(Queue queue) {
//Implement your code here and change the return value accordingly
Queue nqueue = new Queue(queue.getMaxSize());
boolean flag = true;
while(!(queue.isEmpty())){
int val = queue.dequeue();
for(int i=2;i<=10;i++){
if(val%i!=0){
flag=false;
break;
}
}
if(flag){
nqueue.enqueue(val);
}
}
return nqueue;
}
}
You should reset your flag to true before each iteration of your while loop (as you've been suggested already).
In order to avoid such issues, consider extracting the internal loop into a separate method. That will help avoiding nested loop breaking confusion:
public static boolean isDivisible(int value) {
for (int i = 2; i < 10; i++) {
if (value % i > 0) {
return false;
}
}
return true;
}
then simply use it while iterating over your queue:
public static Queue findEvenlyDivisibleNumbers(Queue queue) {
Queue nqueue = new Queue(queue.getMaxSize());
while (!(queue.isEmpty())) {
int value = queue.dequeue();
if (isDivisible(value)) {
nqueue.enqueue(value);
}
}
return nqueue;
}
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();
}
}
}
How do I access the top elements of each stack so I can compare them? I used (iTop,i2Top,nTop,n2Top) because I've been testing to make this work but I can't seem to get the right output.
What am I doing wrong?
I assumed this would work, but it's not either. Basically I want to reference the top element of stack, and compare it to the top element of stack2. Then if they are equal, pop them and do the same for the rest of the stack. At the end, if the stack is empty because all elements were the same and got popped, then it's true the stacks are the same. And push back stack 1 and stack 2.
Thank you
public Boolean sameStack(StackArray<E> s2) {
E t1, t2;
//E iTop = this.items[top];
//E i2Top= s2.items[top];
int nTop = this.top; //
int n2Top= s2.top; // nTop == n2Top is true even when elements are not equal
boolean t = true;
if(this.isEmpty() && s2.isEmpty()) {
return t;
}//if
if(this.top != s2.top) {
t = false;
return t;
}
if(this.items[top] == s2.items[s2.top]){
t1 = this.pop();
t2 = s2.pop();
t = sameStack(s2);
push(t1);
push(t2);
}
else{
t = false;
}
return t;
}
public class StackArray<E> {
private int top=-1;
private static final int MAX_ITEMS = 10;
private E items[];
#SuppressWarnings("unchecked")
public StackArray() {
items = (E[]) new Object[MAX_ITEMS];
System.out.println("Stack Created!");
}
public void push(E e) {
if (isFull()==true) {
System.out.println("Stack Full!");
}
else{
top=top+1;
items[top] = e;
}
}//Push
public E pop() {
if (isEmpty()==true) {
System.out.println("Stack Empty!");
}
else{
E e = (E) items[top];
items[top] = null;
top = top-1;
return e;
}
return null;
} //pop
public boolean isFull() {
if (top == items.length-1) {
return true;
}
return false;
} //isFull
public boolean isEmpty(){
if (top==-1) {
return true;
}
return false;
}//isEmpty
#Override
public String toString()
{
System.out.println("Array:");
System.out.print("{");
for(int i = 0; i < items.length ;i++) {
System.out.print(items[i]+" ");
}
System.out.print("}");
return "";
}//toString
public Boolean sameStack(StackArray<E> s2) {
E t1, t2;
//E iTop = this.items[top];
//E i2Top= s2.items[top];
int nTop = this.top; //
int n2Top= s2.top; // nTop == n2Top is true even when elements are not equal
boolean t = true;
if(this.isEmpty() && s2.isEmpty()) {
return t;
}//if
//This is the part I need to compare the elements
if(nTop == n2Top) {
t1 = this.pop()
t2 = s2.pop();
// t = sameStack(s2);
// push(t1);
// s2.push(t2);
}
return t;
}
public static void main(String[] args)
{
// Code reference for sameStack method
StackArray<Integer> stack = new StackArray<Integer>();
StackArray<Integer> stack2 = new StackArray<Integer>();
stack.push(111);
stack.push(222);
stack.push(7177);
// stack.push(40);
stack2.push(444);
stack2.push(555);
stack2.push(777);
// stack2.push(40);
System.out.println(stack);
System.out.println(stack2);
// //Calling comparison method
if (stack.sameStack(stack2) == true) {
System.out.println("True, both stacks are equal.");
}//if
else {
System.out.println("False, stacks are not equal.");
}//else
System.out.println(stack);
System.out.println(stack2);
}//main
}//class
Just iterate the items array and compare the elements using equals() (not ==).
public boolean sameStack(StackArray<E> s2) {
if (this.top != s2.top) {
return false;
}
for (int i = 0; i <= this.top; i++) {
if (! this.items[i].equals(s2.items[i])) {
return false;
}
}
return true;
}
This works, because any method of StackArray can access private members of StackArray, whether it's the current instance (this) or some other instance (e.g. s2).
If you specifically need to use recursion to test equality of your stacks then an easier method would be to pass the index to the method. Then you don't need to push and pop.
public boolean equals(Stack<E> other) {
return equalsFrom(other, 0);
}
private boolean equalsFrom(Stack<E> other, int from) {
if (from >= this.top || from >= other.top)
return from >= this.top && from >= other.top;
else
return this.items[from].equals(other.items[from])
&& equalsFrom(other, from + 1);
}
Hopefully that method makes sense to you. The first branch of the if statement could be read as "if I've reached the end of either stack then I must have reached the end of both stacks for them to be equal". the second branch could be read as "if I haven't reach the end of either stack then the current element must be equal and the rest of the stacks must be equal for the entire stacks to be equal".
Spongebob meme Many Hours Later...........Figured it out by myself at last!
import java.util.NoSuchElementException;
public class StackArray<E> {
private int top=-1;
private static final int MAX_ITEMS = 10;
private E items[];
#SuppressWarnings("unchecked")
public StackArray() {
items = (E[]) new Object[MAX_ITEMS];
System.out.println("Stack Created!");
}
public void push(E e) {
if (isFull()==true) {
System.out.println("Stack Full!");
}
else{
top=top+1;
items[top] = e;
}
}
public E pop() {
if (isEmpty()==true) {
System.out.println("Stack Empty!");
}
else{
E e = (E) items[top];
items[top] = null;
top = top-1;
return e;
}
return null;
}
public boolean isFull() {
if (top == items.length-1) {
return true;
}
return false;
}
public boolean isEmpty(){
if (top==-1) {
return true;
}
return false;
}
#Override
public String toString()
{
System.out.println("Array:");
System.out.print("{");
for(int i = 0; i < items.length ;i++) {
System.out.print(items[i]+" ");
}
System.out.print("}");
return "";
}
public int peek() {
if (this.isEmpty()) throw new NoSuchElementException("Stack underflow");
//System.out.println("items[top]"+this.items[top]);
//System.out.println("e"+e);
return (int) this.items[top];
}
public Boolean sameStack(StackArray<E> s2) {
E t1, t2;
boolean t = true;
if(this.isEmpty() && s2.isEmpty()) {
return t;
}
if ((int) this.peek() == s2.peek()) {
t1 = this.pop();
t2 = s2.pop();
t = sameStack(s2);
this.push(t1);
s2.push(t2);
}
else {
t = false;
return t;
}
return t;
}
public static void main(String[] args)
{
// Code reference for sameStack method
StackArray<Integer> stack = new StackArray<Integer>();
StackArray<Integer> stack2 = new StackArray<Integer>();
stack.push(122);
stack.push(222);
stack.push(3313);
stack.push(46);
stack2.push(122);
stack2.push(222);
stack2.push(3313);
stack2.push(46);
System.out.println(stack);
System.out.println(stack2);
stack.peek();
if (stack.sameStack(stack2) == true) {
System.out.println("They are equal");
}
else {
System.out.println("They are NOT equal");
}
System.out.println(stack);
System.out.println(stack2);
//Calling comparison method
// stack.sameStack(stack2);
}
}
I have to write code for Dequeue using a circular array I am getting null pointer exceptions that point to my addFront method, I feel like the logic is correct but I just can't seem to get what's wrong. A full queue is indicated by when rear is 2 positions counter clockwise from front. And an empty queue is indicated by when rear is 1 position counter clockwise from front.
Here is my code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Dequeue<E> {
private E elements[];
private int front;
private int rear;
private static final int INITIAL_CAPACITY = 5;
/** Creates a queue with an initial capacity of 5 */
#SuppressWarnings("unchecked")
public Dequeue(int INITIAL_CAPACITY) {
elements = (E[]) new Object[INITIAL_CAPACITY];
front = 0;
rear = -1;
}
public Dequeue() {
front = 1;
rear = 0;
}
public int size() {
return elements.length;
}
public boolean empty() {
return (rear + 1 == front);
}
public boolean isFull() {
return (front == rear + 2);
}
#SuppressWarnings("unchecked")
private void resize() {
E[] temp = (E[]) new Object[(elements.length * 2)+1]; // new array
int i = 0; // use this to control new array positions
int j = front; // use this to control old array positions
boolean rearReached = false;
while (!rearReached) {
rearReached = j % elements.length == rear; // is true if we've reached the rear
temp[i] = elements[j % elements.length];
i++;
j++;
}
front = 0;
rear = elements.length - 1;
elements = temp;
}
public boolean addFront(E item) {
// check whether Deque if full or not
if (isFull()) {
resize();
}
if (elements.length == 0) {
elements[front] = item;
} else if (front == 0){
front = elements.length - 1 ;
elements[front] = item;
} else {
front--;
elements[front] = item;
}
return true;
}
public boolean addRear(E item) {
if (isFull()) {
resize();
rear++;
elements[rear] = item;
} else if (empty()) {
rear++;
elements[rear] = item;
}
return elements[rear] == item;
}
public E peekFront() {
// check whether Deque is empty or not
if (empty()) {
throw new NoSuchElementException("Empty Deque");
}
E result = elements[front];
return result;
}
public E peekRear() {
// check whether Deque is empty or not
if (empty()) {
throw new NoSuchElementException("Empty Deque");
}
E result = elements[rear];
return result;
}
public E removeFront() {
// check whether Deque is empty or not
if (empty()) {
throw new NoSuchElementException("Empty Deque");
}
// Deque has only one element
if (front == rear) {
front = -1;
rear = -1;
} else
// back to initial position
if (front == size() - 1)
front = 0;
else // increment front by '1' to remove current
// front value from Deque
front++;
return elements[front];
}
public E removeRear() {
if (empty()) {
throw new NoSuchElementException("Empty Deque");
}
// Deque has only one element
if (front == rear) {
front = -1;
rear = -1;
} else if (rear == 0)
rear = size() - 1;
else
rear = rear - 1;
return elements[rear];
}
public Iterator<E> iterator() {
Iterator<E> it = new Iterator<E>() {
private int currentIndex = front;
#Override
public boolean hasNext() {
return currentIndex < size() && elements[currentIndex] != elements[rear];
}
#Override
public E next() {
return elements[currentIndex++];
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
}
My Java assignment is to implement a set class by using an array.
The assignment won't allow me import the set class from the library, so I have to make it on my own. When I tried to print out the array, it prints out numbers in repeats, not unique numbers. I don't know where the problem is, so if you guys can find any errors in my code, it would be great. I tried to add numbers 2, 3, and 4 to the set, so the result should be 2 3 4, but the code shows me 2 3 2 3 2.
I think the source of the problem is from the add method from the set class, but I don't know what the problem is exactly.
import java.util.Arrays;
public final class Set implements SetInterface
{
private int[] set;
private int size;
private int capacity;
public Set(int c)
{
capacity = c;
set = new int[capacity];
size = 0;
}
public boolean contains(int x)
{
boolean contains = false;
for(int i = 0; i<capacity; i++)
{
if(x == set[i])
contains = true;
else
contains = false;
}
return contains;
}
public void add(int x)
{
for(int i = 0; i<capacity; i++)
{
if(!contains(x))
{
if(size == capacity)
{
set = Arrays.copyOf(set,size*2);
}
if(set[i]==0)
{
set[i++] = x;
}
}
}
size++;
}
public boolean remove(int x)
{
boolean remove = false;
for(int i = 0; i < capacity; i++)
{
if(x == set[i])
{
set[i] = set[size -1];
size--;
remove = true;
}
if(isEmpty())
{
remove = false;
}
}
return remove;
}
public void clear()
{
set = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
if(size == 0)
return true;
else
return false;
}
public int[] toArray()
{
return Arrays.copyOf(set, capacity);
}
}
This is the driver class that I test my class.
import java.util.Arrays;
public class SetDriver
{
public static void main(String[] args)
{
SetDriver driver = new SetDriver();
Set s1 = new Set(5);
s1.add(2);
s1.add(3);
s1.add(4);
driver.print(s1);
System.out.println("Size: "+s1.size());
}
public static void print(Set s)
{
for(int i = 0; i<s.toArray().length; i++)
{
System.out.print(s.toArray()[i]+" ");
}
System.out.println("");
}
}
The outputs are here:
2 3 2 3 2
Size: 3
There's a likely problem with your contains method. Suppose that you did find a duplicate. What happens is that you assign your variable to true and you continue to iterate. This stomps over the logic entirely; you could have a duplicate but never act on it because your boolean code precludes you from doing so.
Ideally, when you find a match, you must stop iterating and return immediately.
public boolean contains(int value) {
for(int setItem : set) {
if(setItem == value) {
return true;
}
}
return false;
}
You should change add method like this.
public void add(int x) {
if (contains(x))
return;
if (size >= capacity) {
capacity *= 2;
set = Arrays.copyOf(set, capacity);
}
set[size++] = x;
}
I have 3 arrays of 5 items. Inputting an integer that is less than 99 will place it in the first array, inputting an integer from 101 to 199 will put it into the second and 201-299 will put it into the 3rd array.
import java.util.Arrays;
import java.util.Scanner;
public class priorityQueue {
private int[][] queueArray;
}
public priorityQueue() //constructor
{
queueArray = new int[3][5];
}
public void printQueue() {
System.out.println(Arrays.toString(queueArray));
}
public boolean isFull(int[] array){
return (array.length-1 == 5);
}
public boolean enqueue(int item){
//returns true or false if enqueue is not possible
//try lower priority queue(s) if necessary
}
I have no idea how to implement a priority into how integers are inserted, could anyone point me in the right direction?
Here's a rudimentary implementation of the requirements, for what it's worth. Note that you can get your index into the first level of queueArray by using integer division on your item parameter like so: int whichQueue = item / 100;
import java.util.Arrays;
public class PriorityQueue
{
private int[][] queueArray;
public PriorityQueue() // constructor
{
queueArray = new int[3][5];
}
public void printQueue()
{
System.out.println(Arrays.toString(queueArray));
}
public boolean isFull(int[] array)
{
return findEmptySlot(array) < 0;
}
public boolean enqueue(int item)
{
if (item < 1 || item > 299) {
throw new IllegalArgumentException("item must be between 1 and 299");
}
for (int i = item / 100; i < this.queueArray.length; i++) {
if (enqueue(item, this.queueArray[i])) {
return true;
}
}
return false;
}
private boolean enqueue(int item, int[] queue) {
int emptySlot = findEmptySlot(queue);
if (emptySlot >= 0) {
queue[emptySlot] = item;
return true;
}
return false;
}
private int findEmptySlot(int[] queue) {
for (int i = 0; i < queue.length; i++) {
if (queue[i] == 0) {
return i;
}
}
return -1;
}
}