Dequeues in Java using arrays + odd and even numbers - java

I'm having some trouble with my programming exercise in which I should implement dequeues using arrays.
I already got the operations I need but after the implementation you should run through the numbers 1-20 and insert the even numbers at the end of the dequeue and the odd numbers add the beginning.
After that you should use the method removeFront to remove all numbers in the list and should print them on the console.
There is also the hint that the correct output is: (19,17,15...,1,2,4,...,20).
My problem now is that the number 1 is missing in the list and instead it prints out a null value as the first item to be removed.
public class Dequeues<E> {
private final int max;
private int head;
private int tail;
private E[] deque;
private int counter;
public Dequeues(int max) {
this.max = max;
deque = (E[]) new Object[max];
this.head = 0;
this.tail = 0;
this.counter = 0;
}
public boolean isEmpty (){
return (counter == 0);
}
public boolean isFull() {
return(counter>= max);
}
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[head--] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public void addBack(E x){
if(!isFull()) {
if(tail == deque.length-1) {
tail = 0;
deque[tail] = x;
} else {
deque[tail++] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public E removeFront(){
if(!isEmpty()) {
E ret = deque[head];
deque[head++] = null;
if(head >= deque.length) {
head = 0;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public E removeBack(){
if (!isEmpty()) {
E ret = deque[tail];
deque[tail--] = null;
if(tail < 0) {
tail = deque.length-1;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public static void main (String [] args) {
Dequeues test = new Dequeues(20);
for (int i = 1; i <= test.deque.length; i++) {
if(i % 2 == 0) {
test.addBack(i);
} else if(i % 2 == 1) {
test.addFront(i);
}
}
System.out.println("Use of removeFront and output of the values: ");
for (int i = 0; i < test.deque.length; i++) {
System.out.print(test.removeFront() + " ");
}
}}
Output is the following:
Use of removeFront and output of the values:
null 19 17 15 13 11 9 7 5 3 2 4 6 8 10 12 14 16 18 20

You just simply wrong used -- operator.
Right implementation of the addFront method should be:
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[--head] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
So, the difference is here deque[--head] = x;
--head means reduce head value by one and then use it.
head-- means use value head and then reduce its value
Your situation was:
head = deque.length-1; head == 19
head != 0 and you go to the else statement. head value = 19. You used head-- and got again 19 and decremented it by one, but had to use --head.

Related

Trying to figure out what's wrong with my return in my list function

public class Linked {
static class Node {
public Node (double item, Node next) { this.item = item; this.next = next; }
public double item;
public Node next;
}
int N;
Node first;
public int posofLastNine () {
if(first != null) {
int index = 0;
int indexTemp = 0;
for (Node x = this.first; x != null; x=x.next) {
if (x.item == 9.0)
indexTemp = index;
index++;
}
index -= 1;
if (this.first.item == 9.0)
return index;
if (indexTemp == 0)
return -1;
return index - indexTemp;
}
return -1;
}
The point is to return the last index in a list that is 9. That is 0,1,9,9,10 would return 3. The issue is, it needs to return -1 if a 9 does not exist. I cannot figure out what's wrong in my code that's preventing it. I cannot add a function or add to parameters. But that's the only issue.
Your code uses variables and classes that you have not shown us, so I can't discern what's going on there. Please provide more information if you want specific help.
To get the last index of a specific element in an array (or list), the easiest way is to simply iterate backwards through the array. Return the first element that matches your parameters. If the whole array is traversed and no dice, return -1.
Here is an example with int[]:
public static int indexOfLastNine(int[] arrayIn) {
for (int i = arrayIn.length - 1; i >= 0; i--) {
if (arrayIn[i] == 9) return i;
}
return -1;
}
Edit
If we have to use your specific type of Linked list, here is an implementation that will work. Please note that this assumes the last node in the Linked list points to null.
public int posOfLastNine() {
int lastNineIndex = -1;
int currentNodeIndex = 0;
Node currentNode = first;
while (true) {
if (currentNode == null) {
break;
}
if (currentNode.item == 9.0) {
lastNineIndex = currentNodeIndex;
}
currentNodeIndex++;
currentNode = currentNode.next;
}
return lastNineIndex;
}
It seems that the logic to detect the last index of 9.0 is overcomplicated.
It could be refactored like this:
remove null check for first
set resulting index to -1 immediately
remove redundant checks after the loop
always return calculated result
public int posofLastNine () {
int result = -1;
int index = 0;
for (Node x = this.first; x != null; x = x.next) {
if (x.item == 9.0) {
result = index;
}
index++;
}
return result;
}
Test code:
public static boolean test(int pos, String data) {
if (null == data || data.trim().isEmpty()) {
return -1 == pos;
}
String[] s = data.split("\\s");
Node head = null;
if (s.length > 0) {
head = new Node(Double.parseDouble(s[0]), null);
Node curr = head;
for (int i = 1; i < s.length; i++) {
Node next = new Node(Double.parseDouble(s[i]), null);
curr.next = next;
curr = next;
}
}
Linked linked = new Linked();
linked.N = pos;
linked.first = head;
return linked.N == linked.posofLastNine();
}
public static void main(String[] args) {
System.out.println(test(-1, null));
System.out.println(test(-1, ""));
System.out.println(test(0, "9 11 14 31"));
System.out.println(test(-1, "8 11 14 31")); // no 9
System.out.println(test(3, "9 11 9 9 14 16"));
}
Output:
true
true
true
true
true

Design patterns: Iterator pattern

public BigDecimal next() {
for (int i = 1; i < 100; i++) {
BigDecimal cur = new BigDecimal(1);
BigDecimal prev = new BigDecimal(0);
final BigDecimal next = cur.add(prev);
prev = cur;
cur = next;
}
return cur;
}
Could not implement Bigdecimal in this for loop to get Fibonacci numbers
In your code, hasNext is always false.
This tells the consumer of the iterator that we reached the end of the iteration.
This is what you want to achieve
I replaced all BigDecimal references with Integer. If you want to keep as it then needs to make some small changes.
//This is class with main method
import java.util.Iterator;
public class IteratorPattern {
public static void main(String[] args) {
int n = 10;
FibonacciSequence fibonacciSequence = new FibonacciSequence(n);
System.out.println("iteration using iterator for-loop");
//iteration using iterator for-loop
for (Integer fibonacciNumber : fibonacciSequence) {
System.out.println(fibonacciNumber);
}
System.out.println("iteration using iterator");
//iteration using iterator
Iterator<Integer> iterator = fibonacciSequence.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class FibonacciSequence implements Iterable<Integer>, Iterator<Integer> {
private final Integer n;
private Integer a;
private Integer b;
private int c = 1;
FibonacciSequence(Integer n) {
this.n = n;
}
#Override
public Iterator<Integer> iterator() {
return new FibonacciSequence(n);
}
#Override
public boolean hasNext() {
return c <= n;
}
#Override
public Integer next() {
c++;
if (a == null && b == null) {
a = 0;
return 0;
} else if (b == null) {
b = 1;
return b;
} else if (a == 0 && b == 1) {
a = 1;
return b;
}
Integer temp = b;
b = b + a;
a = temp;
return b;
}
}
Output :
iteration using iterator for-loop
0
1
1
2
3
5
8
13
21
34
iteration using iterator
0
1
1
2
3
5
8
13
21
34
Now the point is what changes I made.
As told by #Tom S. your hasNext method should return false if the
count reaches to n.
I changed logic in the next method. Take a look at it.

How to implement a maximum priority queue using a heap-ordered binary tree with a triply-linked Node?

I am trying to implement a max priority queue using a heap binary tree with a triple-linked node. This is the code that I currently have yet when I run it and try to print out the tree nothing prints out it is just empty lines. I am using the helped methods sink and swim in order to help me organize the queue as I add different elements. I am also implementing an ADT (MaxPQ) which just has the public methods that need to be implemented. I was wondering if there is anything that I am doing wrong?
public class LinkedMaxPQ<T extends Comparable<T>> implements MaxPQ<T> {
// Instance variables
Node root;
int size;
Node lastInserted;
// Node inner class definition
// Node class
class Node {
int N;
T info;
Node left;
Node right;
Node parent;
Node(T info, int N) {
this.info = info; this.N = N;
}
}
private void swim(Node x){
if(x == null) return;
if(x.parent == null) return; // we're at root
int cmp = x.info.compareTo(x.parent.info);
if(cmp > 0){
swapNodeData(x, x.parent);
swim(x.parent);
}
}
private void swapNodeData(Node x, Node y){
T temp = x.info;
x.info = y.info;
y.info = temp;
}
private void sink(Node x){
if(x == null) return;
Node swapNode;
if(x.left == null && x.right == null){
return;
}
else if(x.left == null){
swapNode = x.right;
int cmp = x.info.compareTo(swapNode.info);
if(cmp < 0)
swapNodeData(swapNode, x);
} else if(x.right == null){
swapNode = x.left;
int cmp = x.info.compareTo(swapNode.info);
if(cmp < 0)
swapNodeData(swapNode, x);
} else{
int cmp = x.left.info.compareTo(x.right.info);
if(cmp >= 0){
swapNode = x.left;
} else{
swapNode = x.right;
}
int cmpParChild = x.info.compareTo(swapNode.info);
if(cmpParChild < 0) {
swapNodeData(swapNode, x);
sink(swapNode);
}
}
}
String printThisLevel (Node rootnode, int level) {
StringBuilder s = new StringBuilder();
// Base case 1: if the current rootnode is null, return the current string.
if (rootnode == null) {
return s.toString();
}
// Base case 2: If you're at the first level, append the
// info field of the current rootnode.
if (level == 1) {
s.append( rootnode.info.toString());
}
// Recursive calls: otherwise call the method on the left
// and on the right of the next lower level.
else if (level > 1) {
s.append( printThisLevel(rootnode.left, level-1));
s.append( printThisLevel(rootnode.right, level-1));
}
return s.toString();
}
private int size(Node x){
if(x == null) return 0;
return x.N;
}
private Node insert(Node x, T data){
if(x == null){
lastInserted = new Node(data, 1);
return lastInserted;
}
// compare left and right sizes see where to go
int leftSize = size(x.left);
int rightSize = size(x.right);
if(leftSize <= rightSize){
// go to left
Node inserted = insert(x.left, data);
x.left = inserted;
inserted.parent = x;
} else{
// go to right
Node inserted = insert(x.right, data);
x.right = inserted;
inserted.parent = x;
}
x.N = size(x.left) + size(x.right) + 1;
return x;
}
private Node resetLastInserted(Node x){
if(x == null) return null;
if(x.left == null && x.right == null) return x;
if(size(x.right) < size(x.left))return resetLastInserted(x.left);
else return resetLastInserted(x.right);
}
public void insert(T data){
root = insert(root, data);
swim(lastInserted);
}
public T getMax(){
if(root == null) return null;
return root.info;
}
public T removeMax(){
if(size() == 1){
T ret = root.info;
root = null;
return ret;
}
swapNodeData(root, lastInserted);
Node lastInsParent = lastInserted.parent;
T lastInsData = lastInserted.info;
if(lastInserted == lastInsParent.left){
lastInsParent.left = null;
} else{
lastInsParent.right = null;
}
Node traverser = lastInserted;
while(traverser != null){
traverser.N--;
traverser = traverser.parent;
}
lastInserted = resetLastInserted(root);
sink(root);
return lastInsData;
}
public int size(){
return size(root);
}
public boolean isEmpty(){
return size() == 0;
}
public String toString() {
// Create a StringBuilder object to make it more efficient.
StringBuilder sb=new StringBuilder();
// get the height of the tree
int height = (int)Math.ceil(Math.log(size+1) / Math.log(2));
// for each level in the tree, call printThisLevel and
// append the output to the StringBuilder
for (int i=1; i<=height; i++) {
sb.append("level " + i + ": "+ printThisLevel(this.root, i) + "\n");
}
// Return the string of the StringBuilder object
return sb.toString();
}
public static void main (String[] args) {
LinkedMaxPQ<String> t = new LinkedMaxPQ<String>();
t.insert("a");
System.out.println(t.toString());
t.insert("b");
t.insert("c");
t.insert("d");
t.insert("e");
t.insert("f");
t.insert("g");
t.insert("h");
t.insert("i");
t.insert("j");
t.insert("k");
t.size();
t.removeMax();
t.getMax();
t.removeMax();
t.insert("x");
t.insert("y");
t.removeMax();
t.getMax();
System.out.println(t.toString());
}
}
In this line:
int height = (int)Math.ceil(Math.log(size+1) / Math.log(2));
size should be size().
int height = (int)Math.ceil(Math.log(size()+1) / Math.log(2));
After this correction, the results are coming out.
However, there is a logic problem, which needs a solution.
For test case, testdata = new int[] {3, 5, 2, -7, 9, 4, 7};
The result is 9 4 7 -7 3 2 5
But correct result should be 9 5 7 -7 3 2 4 (from another array implementation).
I know the mistake comes from when at the 3rd levle, insert data {9}, its parent should be the 2nd leverl data {3} on the left, not the {2} on the right. Any thought to solve it?

Recursive to Non recursive, troubling me for awhile now

F(n):
if n >= 6:
F(n/3)
F(2*n/3)
print n
How would I turn this into a nonrecursive function? ive tried to use two while loops one for the n/3 case and one for the 2*n/3 case but nothing outputs the right things
public static void F2Stack(int n) {
Stack stack2 = new Stack();
int current = n;
int current2 = n;
while(current >= 6) {
current = current/3;
stack2.push(current);
}
while(current2 >= 6) {
current2 = current2*2/3;
stack2.push(current2/3);
stack2.push(current2*2/3);
stack2.push(current2);
}
while(!(stack2.isEmpty())){
System.out.println(stack2.pop());
}
}
Damn Corono Virus Lockdown! it took four or five hours today, but we got something. The hard part was java is not capable to do "go to label" I guess. Only you can do "continue/break label". Anyway hope this helps someone;
public static void main(String[] args) {
System.out.println("vvvv 18 recursive vvvv");
recursive(18);
System.out.println("vvvv 18 nonrecursive vvvv");
nonRecursive(18);
System.out.println("vvvv 25 recursive vvvv");
recursive(25);
System.out.println("vvvv 25 nonrecursive vvvv");
nonRecursive(25);
System.out.println("vvvv 31 recursive vvvv");
recursive(25);
System.out.println("vvvv 31 nonrecursive vvvv");
nonRecursive(25);
}
static void doJob(int n) {
System.out.println(n);
}
static void recursive(int number) {
if (number >= 6) {
recursive(number/3);
recursive(2*number/3);
}
doJob(number);
}
static void nonRecursive(int number) {
// a basic context
class Ctx {
int n, m;
boolean bn, bm;
public Ctx(int num) {
n = num / 3;
// do not try m = 2 * n :)
m = 2 * num / 3;
}
};
// how many times can we change the context?
// we will use here a bit math
int d = 2 * ((int)(Math.log(2 * number)/Math.log(3)) + 1);
Ctx[] ctx = new Ctx[d];
// current context
ctx[0] = new Ctx(number);
int i = 0;
while (number >= 6 && ctx[0] != null) {
// do n/3
if (ctx[i].n >= 6 && !ctx[i].bn) {
i++;
ctx[i] = new Ctx(ctx[i-1].n);
continue;
}
// we reached as deep as poosible for n/3
if (!ctx[i].bn) {
doJob(ctx[i].n);
ctx[i].bn = true;
}
// now do 2*n/3
if (ctx[i].m >= 6 && !ctx[i].bm) {
i++;
ctx[i] = new Ctx(ctx[i-1].m);
continue;
}
if (!ctx[i].bm) {
doJob(ctx[i].m);
ctx[i].bm = true;
}
// we are done with this context
ctx[i] = null;
if (i > 0) {
i--;
if (!ctx[i].bn) {
doJob(ctx[i].n);
ctx[i].bn = true;
} else if (!ctx[i].bm) {
doJob(ctx[i].m);
ctx[i].bm = true;
}
}
}
doJob(number);
}

Autocomplete byReverseWeightOrder comparator issue

I have been working on this problem for several hours now and I just cannot figure out what I am doing wrong here. Could anyone help point me in the right direction?
I was asked to write an Autocomplete program and I've completed everything except for this one method I cannot get working. Each term has: 1. String query and 2. long weight.
Here is the method:
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() { // LINE CAUSING PROBLEM
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) { // LINE CAUSING PROBLEM
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
My problem is that no matter how I mess with the method I always result in a NullPointerException(). Which, it points to this method (byReverseWeightOrder) as well as these two statements.
Arrays.sort(matches, Term.byReverseWeightOrder());
Term[] results = autocomplete.allMatches(prefix);
Here is the rest of the code if it can be found helpful:
Term
import java.util.Comparator;
public class Term implements Comparable<Term> {
public String query;
public long weight;
public Term(String query, long weight) {
if (query == null) {
throw new java.lang.NullPointerException("Query cannot be null");
}
if (weight < 0) {
throw new java.lang.IllegalArgumentException("Weight cannot be negative");
}
this.query = query;
this.weight = weight;
}
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() {
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) {
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
public static Comparator<Term> byPrefixOrder(int r) {
if (r < 0) {
throw new java.lang.IllegalArgumentException("Cannot order with negative number of characters");
}
final int ref = r;
return
new Comparator<Term>() {
public int compare(Term t1, Term t2) {
String q1 = t1.query;
String q2 = t2.query;
int min;
if (q1.length() < q2.length()) {
min = q1.length();
}
else {
min = q2.length();
}
if (min >= ref) {
return q1.substring(0, ref).compareTo(q2.substring(0, ref));
}
else if (q1.substring(0, min).compareTo(q2.substring(0, min)) == 0) {
if (q1.length() == min) {
return -1;
}
else {
return 1;
}
}
else {
return q1.substring(0, min).compareTo(q2.substring(0, min));
}
}
};
}
public int compareTo(Term that) {
String q1 = this.query;
String q2 = that.query;
return q1.compareTo(q2);
}
public long getWeight() {
return this.weight;
}
public String toString() {
return this.weight + "\t" + this.query;
}
}
BinarySearchDeluxe
import java.lang.*;
import java.util.*;
import java.util.Comparator;
public class BinarySearchDeluxe {
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) <= 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
return -1;
}
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a == null || a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) < 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
return -1;
}
}
AutoComplete
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
public class Autocomplete {
public Term[] terms;
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new java.lang.NullPointerException();
}
this.terms = terms.clone();
Arrays.sort(this.terms);
}
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int count = start;
System.out.println("Start: " + start + " End: " + end);
if (start == -1 || end == -1) {
// System.out.println("PREFIX: " + prefix);
throw new java.lang.NullPointerException();
} // Needed?
Term[] matches = new Term[end - start + 1];
//matches = Arrays.copyOfRange(terms, start, end);
for (int i = 0; i < end - start; i++) {
matches[i] = this.terms[count];
count++;
}
Arrays.sort(matches, Term.byReverseWeightOrder());
System.out.println("Finished allmatches");
return matches;
}
public int numberOfMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
System.out.println("Finished numberMatches");
return end - start + 1; // +1 needed?
}
public static void main(String[] args) throws IOException {
// Read the terms from the file
Scanner in = new Scanner(new File("wiktionary.txt"));
int N = in.nextInt(); // Number of terms in file
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.nextLong(); // read the next weight
String query = in.nextLine(); // read the next query
terms[i] = new Term(query.replaceFirst("\t",""), weight); // construct the term
}
Scanner ip = new Scanner(System.in);
// TO DO: Data Validation Here
int k;
do {
System.out.println("Enter how many matching terms do you want to see:");
k = ip.nextInt();
} while (k < 1 || k > N);
Autocomplete autocomplete = new Autocomplete(terms);
// TO DO: Keep asking the user to enter the prefix and show results till user quits
boolean cont = true;
do {
// Read in queries from standard input and print out the top k matching terms
System.out.println("Enter the term you are searching for. Enter * to exit");
String prefix = ip.next();
if (prefix.equals("*")) {
cont = false;
break;
}
Term[] results = autocomplete.allMatches(prefix);
System.out.println(results.length);
for(int i = 0; i < Math.min(k,results.length); i++)
System.out.println(results[i].toString());
} while(cont);
System.out.println("Done!");
}
}
I apologize for the sloppy code, I have been pulling my hair out for awhile now and keep forgetting to clean it up.
Two examples:
Example 1:
int k = 2;
String prefix = "auto";
Enter how many matching terms do you want to see:
2
Enter the term you are searching for. Enter * to exit
auto
619695 automobile
424997 automatic
Example 2:
int k = 5;
String prefix = "the";
Enter how many matching terms do you want to see:
5
Enter the term you are searching for. Enter * to exit
the
5627187200 the
334039800 they
282026500 their
250991700 them
196120000 there

Categories

Resources