JAVA how to implement wraparound on a deque - java

I am trying to implement wraparound on my double ended queue and for some reason my insertRight() and removeRight() methods are outputting wrong and my removeLeft() method is just throwing an error. I have looked around and I cannot seem to find an answer to why my methods are not working here they are:
public void insertRight(int newItem) {
if (isFull() == true) {
System.out.print("Full");
} // end of if
else {
if (right == capacity) {
right = 0;
} // end of nested if
else {
deque[right] = newItem;
nElems++;
right++;
} // end of nested else
} // end of else
}// end of insertRight
public void removeRight() {
if (isEmpty() == true) {
System.out.println("Empty");
} // end of if
if (isEmpty() == false) {
System.out.println(right);
if (right == capacity) {
right = 0;
} // end of nested if
int temp = deque[right];
right++;
nElems--;
} // end of if
}// end of removeRight
public void removeLeft() {
if (isEmpty() == true) {
System.out.println("Empty");
} // end of if
if (isEmpty() == false) {
if (left == capacity) {
left = -1;
} // end of nested if
else {
System.out.println(left);
int temp = deque[left];
left++;
nElems--;
} // end of else
} // end of if
}// end of removeLeft

A little more information on the actual meaning/values of left and right would be helpful.
At first glance, it looks like removeLeft() fails because the wrap-around point for left would be 0, not capacity, if my understanding of your code so far is correct.
Also, negative array indices do not work in java. You'll want to refer to the actual last index directly.
And I really recommend looking into code formatting. Your indentation makes it very hard to tell where one block ends and a new one begins. You could save yourself explicit comments by just following a consistent indentation pattern:
public void insertRight(int newItem) {
if (isFull()) {
System.out.print("Full");
} else {
if (right == capacity) {
right = 0;
} else {
deque[right] = newItem;
nElems++;
right++;
}
}
}
public void removeRight() {
if (isEmpty()) {
System.out.println("Empty");
} else {
System.out.println(right);
if (right == capacity) {
right = 0;
}
int temp = deque[right];
right++;
nElems--;
}
}
public void removeLeft() {
if (isEmpty()) {
System.out.println("Empty");
} else {
// My assumption inserted here:
if (left == 0) {
left = capacity - 1;
} else {
System.out.println(left);
int temp = deque[left];
left++;
nElems--;
}
}
}

I see a couple of issues here:
if (right == capacity) {
right = 0;
} // end of nested if
else {
deque[right] = newItem;
nElems++;
right++;
} // end of nested else
If right == capacity you reset the index but don't insert newItem to the array.
It should be something like this (directly typed, not tested):
if (right == capacity) {
right = 0;
} // end of nested if
deque[right] = newItem;
nElems++;
right++;
Now to your removeRight-method:
System.out.println(right);
if (right == capacity) {
right = 0;
} // end of nested if
int temp = deque[right];
right++;
nElems--;
Here you use the same algorithm to check boundaries but it should be a "mirror" to the one you used in insertRight, so something like this (directly typed, not tested):
System.out.println(right);
if (right == 0) {
right = capacity;
} // end of nested if
int temp = deque[right - 1];
right--;
nElems--;
And finally removeLeft:
if (left == capacity) {
left = -1;
} // end of nested if
else {
System.out.println(left);
int temp = deque[left];
left++;
nElems--;
} // end of else
Without the insertLeft method, I can only guess that it has similar problems.

Related

Circular Queue toString method ignoring some conditions

when I call my toString() method it doesn't work if after the index wraps around (front > rear). I have included the code below. After, I enqueue(5) and enqueue(6), the toString seems to be completely ignored. At first I thought I wasn't overriding the default toString in Java but the first print statement clearly tells me I am. Anyways, check the code out:
public class driver {
public static void main(String[] args) {
Queue queue = new Queue(4);
System.out.println(queue);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
System.out.println(queue);
queue.dequeue();
System.out.println(queue);
queue.dequeue();
System.out.println(queue);
queue.enqueue(5);
queue.enqueue(6);
System.out.println(queue);
}
public static class Queue {
int front;
int rear;
int capacity;
int[] queue;
public Queue(int size) {
this.capacity = size;
this.front = this.rear = -1;
this.queue = new int[capacity];
}
#Override
public String toString() {
String str = "";
if (front > rear) {
int i = front;
while (i != rear) {
str = str + queue[i % queue.length] + " ";
i++;
}
//str= str+queue[rear];
}
if (front < rear) {
for (int i = front; i <= rear; i++) {
str = str + queue[i];
}
}
if (front == rear) {
str = "This Queue is Empty. Please Enqueue";
}
return str;
}
public boolean isFull() {
return ((rear == this.queue.length - 1 && front == 0) || rear == front - 1);
}
public boolean isEmpty() {
return (front == -1);
}
public void enqueue(int elem) {
if (isFull()) {
System.out.println("Full Queue - dequeue an element if you need to add an element in the queue");
} else {
if (isEmpty()) {
this.queue[++rear] = elem;
front = 0;
} else {
rear = (rear + 1) % this.queue.length;
this.queue[rear] = elem;
}
}
}
public int dequeue() {
if (isEmpty()) {
System.out.println("empty queue. Enqueue some elments. ");
return -1;
} else {
int store = this.queue[front];
if (rear == front) {
front = rear = -1;
} else {
front = front + 1 % this.queue.length;
}
return store;
}
}
}
*there is a return curly bracket here too lol still new to posting questions. P.S can someone help me because apparently I posted too much code in my question. Any workarounds?
The issue is with i++ in your while loop of toString.
Consider the case where front = 3 and rear = 1 then you start the loop with i = front = 3. However, you keep incrementing until you reach i == rear which will never happen since rear < front
What you want is for i to loop back around to 0 once it reaches capacity.
You can do this by removing i++ and replacing it with i = (i + 1) % capacity;
It seems like you have a different bug in your code, because when I run it I see
This Queue is Empty. Please Enqueue
1234
234
34
3 4 5
You'll need to figure this one out by yourself.
You can even condense it into a single for statement
for(int i = front; i != rear; i = (++i) % capacity)

How do I write my method for balancing my BST?

So I have written an implementation of a BST in Java. My goal is to make it balanced aswell, more precisly an AVL tree. I am having some problem though, I don't know how to implement the trinodeRestructering method(ie the method that balances the tree) I have tried various things but these pointers are sometimes difficult to deal with and I am not sure how to do this recursivly. Down below is my code for adding a new element and the method to check if we are more than 2 steps difference in the tree.
add and balancing method:
private TreeNode insert(TreeNode currN, TreeNode newN) {
if (currN == null) {
return newN;
}
if (currN.getData() == newN.getData()) {
throw new IllegalArgumentException("Value already exists.");
}
if (newN.getData() < currN.getData()) {
if (currN.getLeft() == null) {
currN.setLeft(newN);
} else {
insert(currN.getLeft(), newN);
}
} else {
if (currN.getRight() == null) {
currN.setRight(newN);
} else {
insert(currN.getRight(), newN);
}
}
if (needBalancing()) {
trinodeRestructering(currN);
}
return currN;
}
private TreeNode trinodeRestructering(TreeNode currN) {
//Not sure what to do here.
return currN;
}
height checking method.
public boolean needBalancing(){
if(height(root) == -1){ // true if we need to balance
return true;
}else{
return false;
}
}
private int height(TreeNode node){
if (node == null)
return 0;
int left = height(node.getLeft());
int right = height(node.getRight());
if (left == -1 || right == -1)
return -1;
if (Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
I might add that I got an working inOrder method, perhaps I could use it to balance my tree?

infinite loop in siftDown method for a heap using linked nodes

In my siftDown method for my heap, I'm getting an infinite loop I believe that is being caused by my if(current.isLeaf()) line. Can anyone help me so that I can get Node n down to where it becomes a leaf or when it stops being smaller than its children?
public void siftDown(Node<V> n) {
Node<V> current = n;
boolean notDone = true;
while (notDone) {
if (!current.isLeaf()) {
current = n;
if ((current.data.compareTo(current.left.data) < 0)
&& (current.left.data.compareTo(current.right.data) >= 0)) {
swapValues(current, current.left);
current = current.left;
} else if ((current.data.compareTo(current.right.data) < 0)
&& (current.right.data.compareTo(current.left.data) > 0)) {
swapValues(current, current.right);
current = current.right;
if (current.isLeaf()) {
notDone = false;
}
}
} else {
notDone = false;
}
}
}
public void swapValues(Node<V> x, Node<V> y) {
V temp = x.data;
x.data = y.data;
y.data = temp;
}
public boolean isLeaf() { //inside my node class
if (left == null && right == null)
return true;
else
return false;
}

I can not make my Skyline algorithm use right my ''delete'' method and delete all the right Points of my List ( List with <<Random>> Points)

public void findSkyline1(ListDoublePoints list)
{
DoublePoint p = list.first;
DoublePoint q = list.first;
while (p!=null ){
while (q!=null )
{
if (p.x < q.x)
{
if(p.y<=q.y)
{
list.delete(q);
}
}
else if (p.x == q.x)
{
if (p.y <q.y)
{
list.delete(q);
}
else if (p.y > q.y)
{
list.delete(p);
break;
}
}
else
{
list.delete(p);
break;
}
//end of if
q=q.next;
}
p=p.next;
}
}
.....................
public DoublePoint delete(DoublePoint del)
{
if (del == first)
first = del.next;
else
del.previous.next = del.next;
if (del == last)
last = del.previous;
else
del.next.previous = del.previous;
return del;
}
.........
i have put a list of Random double numbers.My Main calls an algorithm and uses a skyline algorithm(in my own way).In my class about ''ListDoublePoints'' i have a method that deletes the ''DoublePoints'' i don't need.
So,i want to make my delete method work in my skyline algorithm.It works only for a small number of DoublePoints,so some that i don't need...still exist.!Any ideas?

Testing parentheses in a equation using stack java

I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}

Categories