How to implement remove method in Trie data structure? - java

I am trying to implement PatriciaTrie data structure. I was recently asked this question in a coding interview through Google Docs. But I was not able to answer this.
I made some progress by adding insert method in the below code but got stuck on the remove method in the PatriciaTrie code - not sure how to implement that -
Below is my PatriciaTrie code -
public class PatriciaTrie {
protected static class Edge {
Node target;
TTString label;
public Edge(Node target, TTString label) {
this.target = target;
this.label = label;
}
}
protected static class Node {
Edge[] edges; // the children of this node
int numberOfChildren; // the number of children
public Node() {
edges = new Edge[128];
numberOfChildren = 0;
}
}
/**
* number of strings stored in the trie
*/
protected int number;
/**
* This is root
*/
protected Node root;
public PatriciaTrie() {
root = new Node();
number = 0;
}
/**
* Add the x to this trie
* #param x the string to add
* #return true if x was successfully added or false if x is already in the trie
*/
public boolean insert(TTString x) {
Node current = root;
for (int i = 0; i < x.length(); i++) {
TTString ch = x.subString(i, 1);
if (current.edges[x.charAt(i)] != null) {
Node child = current.edges[x.charAt(i)].target;
current = child;
} else {
current.edges[x.charAt(i)] = new Edge(new Node(), ch);
current.numberOfChildren++;
current = current.edges[x.charAt(i)].target;
}
if (i == x.length() - 1)
return true;
}
return false;
}
/**
* Remove x from this trie
* #param x the string to remove
* #return true if x was successfully removed or false if x is not stored in the trie
*/
public boolean remove(TTString x) {
// not sure how to do this
return false;
}
}
And below is my TTString class -
public class TTString {
int i; // index of first character
int m; // length
byte[] data; // data
public TTString(String s) {
data = s.getBytes();
i = 0;
m = s.length();
}
protected TTString(byte[] data, int i, int m) {
this.data = data;
this.i = i;
this.m = m;
}
public TTString subString(int j, int n) {
if (j < 0 || j >= m) throw new IndexOutOfBoundsException();
if (n < 0 || j + n > m) throw new IndexOutOfBoundsException();
return new TTString(data, i+j, n);
}
/**
* The length of this string
* #return
*/
public int length() {
return m;
}
/**
* Return the character at index j
* #param j
* #return
*/
public char charAt(int j) {
return (char)data[i+j];
}
}
Any thoughts on how to implement remove method here?

One idea is: descend from the root to the leaf corresponding to the last character of x (assuming there is path containing x, otherwise there's nothing to change), remembering last fork on your path in the process (first fork is at the root). When you at the leaf, remove all edges/nodes from the last fork till the leaf.

I have implemented it in C# on TRIE data structure for the string code is follow. You can see the complete code here http://devesh4blog.wordpress.com/2013/11/16/real-time-auto-complete-using-trie-in-c/
public void RemoveWord(string word, TRIENode rootNode, string id)
{
int len = word.Length;
if (len == 0)
{
rootNode.PrefixCount--;
if (rootNode.PrefixCount == 0)
rootNode.IsCompleteWord = false;
rootNode.Ids.Remove(id);
return;
}
for (int i = 0; i < len; i++)
{
string key = word.Substring(i, 1);
string lowerVersionKey = key.ToLower();
rootNode.PrefixCount--;
rootNode = rootNode.Children[lowerVersionKey];
}
rootNode.Ids.Remove(id);
if (rootNode.Ids.Count == 0)
rootNode.IsCompleteWord = false;
}

This is my code and sample tests:
protected static class Edge {
Node target;
TTString label;
public Edge(Node target, TTString label) {
this.target = target;
this.label = label;
}
}
protected static class Node {
Edge[] edges; // the children of this node
int numberOfChildren; // the number of children
// isEnd is true means this node is a string's end node.
boolean isEnd;
public Node() {
edges = new Edge[128];
numberOfChildren = 0;
isEnd = false;
}
}
/**
* number of strings stored in the trie
*/
protected int number;
/**
* This is root
*/
protected Node root;
public PatriciaTrie() {
root = new Node();
number = 0;
}
/**
* Add the x to this trie
*
* #param x
* the string to add
* #return true if x was successfully added or false if x is already in the
* trie
*/
public boolean insert(TTString x) {
// not sure what I am supposed to do here?
Node current = root;
for (int i = 0; i < x.length(); i++) {
TTString ch = x.subString(i, 1);
if (current.edges[x.charAt(i)] != null) {
Node child = current.edges[x.charAt(i)].target;
current = child;
} else {
current.edges[x.charAt(i)] = new Edge(new Node(), ch);
current.numberOfChildren++;
current = current.edges[x.charAt(i)].target;
}
if (i == x.length() - 1) {
// mark this node is the string x's end node.
current.isEnd = true;
return true;
}
}
return false;
}
// find the string x in the trie, if true, return the x.
public TTString find(TTString x) {
boolean isOk = false;
Node current = root;
for (int i = 0; i < x.length(); i++) {
if (current.edges[x.charAt(i)] != null) {
current = current.edges[x.charAt(i)].target;
} else {
isOk = false;
}
if (i == x.length() - 1 && current.isEnd == true) {
isOk = true;
}
}
if (isOk == false)
return null;
else
return x;
}
public boolean remove(TTString x) {
Node current = root;
for (int i = 0; i < x.length(); i++) {
if (current.edges[x.charAt(i)] != null) {
current = current.edges[x.charAt(i)].target;
} else {
return false;
}
if (i == x.length() - 1) {
// delete the string x.
current.isEnd = false;
return true;
}
}
return false;
}
void run() {
/*
* Here is the sample patricialTrie whose edges are labeled with
* letters.
*/
TTString tmp = new TTString("ABCD");
System.out.println(insert(tmp) ? "YES" : "NO");
Node current = root;
for (int i = 0; i < tmp.length(); i++) {
System.out.println(current.edges[tmp.charAt(i)].label.charAt(0));
current = current.edges[tmp.charAt(i)].target;
}
tmp = new TTString("ABCDE");
insert(tmp);
tmp = new TTString("ABDF");
insert(tmp);
/*
* remove method
*/
tmp = new TTString("ABCDE");
System.out.println(remove(tmp) ? "YES" : "NO");
System.out.println(find(tmp) == null ? "NULL" : find(tmp));
tmp = new TTString("ABCD");
System.out.println(find(tmp) == null ? "NULL" : find(tmp));
}
public static void main(String args[]) {
new PatriciaTrie().run();
}

Related

B-Tree implementing toString method in Node Class that is giving this error: Cannot invoke forEach((<no type> c) -> {}) on the array type Node<E>[]]

I have Implemented B-Tree, I have given toString to Implement method in Node class as it but its giving errot in this line children.forEach(c ->builder.append(c.toString(depth + 1))); I have tried various methods but not worked
here is other B-Tree files and pdf where is given toString Methods and other Instruction check out these files
toString code
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Node<E extends Comparable<E>> {
public int nodeLocation;
public int index;
private E[] keys = null;
int keysSize = 0;
public Node<E>[] children = null;
public Node<E>[] elements;
int childrenSize = 0;
private Comparator<Node<E>> comparator = new Comparator<Node<E>>() {
#Override
public int compare(Node<E> arg0, Node<E> arg1) {
return arg0.getKey(0).compareTo(arg1.getKey(0));
}
};
protected Node<E> parent = null;
Node(Node<E> parent, int maxKeySize, int maxChildrenSize) {
this.parent = parent;
this.keys = (E[]) new Comparable[maxKeySize + 1];
this.keysSize = 0;
this.children = new Node[maxChildrenSize + 1];
this.childrenSize = 0;
}
E getKey(int index) {
return keys[index];
}
int indexOf(E value) {
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value))
return i;
}
return -1;
}
void addKey(E value) {
keys[keysSize++] = value;
Arrays.sort(keys, 0, keysSize);
}
E removeKey(E value) {
E removed = null;
boolean found = false;
if (keysSize == 0)
return null;
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value)) {
found = true;
removed = keys[i];
} else if (found) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
}
if (found) {
keysSize--;
keys[keysSize] = null;
}
return removed;
}
E removeKey(int index) {
if (index >= keysSize)
return null;
E value = keys[index];
for (int i = index + 1; i < keysSize; i++) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
keysSize--;
keys[keysSize] = null;
return value;
}
int numberOfKeys() {
return keysSize;
}
Node<E> getChild(int index) {
if (index >= childrenSize)
return null;
return children[index];
}
int indexOf(Node<E> child) {
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child))
return i;
}
return -1;
}
boolean addChild(Node<E> child) {
child.parent = this;
children[childrenSize++] = child;
Arrays.sort(children, 0, childrenSize, comparator);
return true;
}
boolean removeChild(Node<E> child) {
boolean found = false;
if (childrenSize == 0)
return found;
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child)) {
found = true;
} else if (found) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
}
if (found) {
childrenSize--;
children[childrenSize] = null;
}
return found;
}
Node<E> removeChild(int index) {
if (index >= childrenSize)
return null;
Node<E> value = children[index];
children[index] = null;
for (int i = index + 1; i < childrenSize; i++) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
childrenSize--;
children[childrenSize] = null;
return value;
}
int numberOfChildren() {
return childrenSize;
}
/**
* {#inheritDoc}
*/
public String toStringg() {
return toString(0);
}
// // based on what toString() does, think about what ‘elements’ and ‘children’
// can be
private String toString(int depth) {
StringBuilder builder = new StringBuilder();
String blankPrefix = new String(new char[depth]).replace("\0", "\t");
List<String> printedElements = new LinkedList<>();
for (Node<E> e : elements)
printedElements.add(e.toString());
String eString = String.join(" :: ", printedElements);
builder.append(blankPrefix).append(eString).append("\n");
children.forEach(c -> builder.append(c.toString(depth + 1))); // this line is giving error
return builder.toString();
}
}
I Have Gievn pdf File where is gievn insructions and code implement I have tried to change childern but not worked I am bound to not make changes in gievn toString method
Arrays in Java doesn't declare their own behavior (don't try to reproduce your experience from languages like JavaScript and TypeScript, where Arrays have methods).
Therefore, you can't invoke method forEach() on the children array (this method is accessible with implementations of Iterable interface, like Collections).
You can use an enhanced for-loop instead:
for (Node<E> node : children) {
builder.append(node.toString(depth + 1));
}
Alternatively, if you declare the property children as a List you'll be able use forEach() with it:
public List<Node<E>> children;
Judging by your assignment requirements, that what you're expected to do.
That would require changing all the methods that make use of children because you can't dial with a List in the same way as with an array. I.e. you would need to use the behavior of the List interface.
children[i] would turn to children.get(i). And children[i] = ... would become children.set(i, ...), or children.add(...).

How to implement a method to find the smallest child in a D-heap Priority Queue

I have a remove method in a Priority Queue class I created from scratch for an assignment. The priority queue I created is held in an array, with the index starting at 0. I keep track of size which is equal to the arrays length. The remove method uses a helper method entitled:
public int findSmallest(int parent)
where parent is the position in the array that the parent is stored at, and I am looking to return its smallest child. Order is simply the number of children each node that is not a leaf has. The code for my findSmallest:
public int findSmallest(int parent) {
int child = parent * order + 1;
int smallest = child;
for (int i = child; i < order + child; ++i) {
if (size >= i) {
return child;
}
if (queue[i].priority <= queue[smallest].priority) {
smallest = child;
}
}
return child;
}
It is currently an array out of bounds exception
Complete implementation of PriorityQueue Class I created:
import java.util.*;
public class PriorityQueue {
private class Item {
private int priority;
private Object data;
private Item(int p, Object d) {
priority = p;
data = d;
}
}
private Item queue[];
private int order;
private int size;
public PriorityQueue(int ord, int s) {
queue = new Item[s];
order = ord;
size = 0;
}
public int getPriority() {
if (size > 0) {
return queue[0].priority;
}
// -55 signifies that the queue is empty
return -55;
}
public Object getData() {
if (size > 0) {
return queue[0].priority;
}
return null;
}
public void remove() {
if (empty() == true) {
System.out.println("Queue is empty, there is nothing to remove.");
return;
}
Item x = queue[size - 1];
size--;
int child = 1;
int parent = 0;
while (child <= size) {
child = findSmallest(parent);
for (int i = order * parent + 1; i < child + order; i++) {
if (child < size && queue[i].priority < queue[child].priority)
child = i;
}
if (x.priority < queue[child].priority)
break;
else {
parent = child;
queue[(child - 1) / order] = queue[child];
child = order * child + 1;
}
}
queue[(child - 1) / order] = x;
}
public int findSmallest(int parent) {
int child = parent * order + 1;
int smallest = child;
for (int i = child; i < order + child; ++i) {
if (size >= i) {
return child;
}
if (queue[i].priority <= queue[smallest].priority) {
smallest = child;
}
}
return child;
}
public int getSize() {
return size;
}
public boolean full() {
return size == queue.length;
}
public boolean empty() {
if (size > 0) {
return false;
}
return true;
}
public void insert(int p, Object d) {
// 1. Create a new Item and add it to queue[size]
// Somewhere store new node created as TEMP
// 2. while loop
// 3. check if node has parent
// 4. if it does --> check if parent.priority > child.priority
// 5. if yes, swap
if (full() == true) {
System.out.println("Queue is full, cannot add new node.");
return;
}
queue[size] = new Item(p, d);
sort();
size++;
}
// Sort() swaps new child node with parents if child.priority < parent.priority
public void sort() {
int child = size;
Item temp = queue[child];
while ( child > 0 && queue[child].priority < queue[(child-1)/(order)].priority) {
queue[child] = queue[(child-1)/order];
queue[(child-1)/order] = temp;
child = ((child - 1) / order);
}
queue[child] = temp;
}
public static void main(String[] args) {
PriorityQueue p1 = new PriorityQueue(5, 100);
PriorityQueue p2 = new PriorityQueue(6, 100);
PriorityQueue p3 = new PriorityQueue(7, 100);
int p = -1; //pointless initialization to keep the compiler happy
p1.insert(0, new Integer(0));
System.out.println("First insert");
for (int i = 1; i < 100; i++)
p1.insert(i, new Integer(i));
for (int i = 0; i < 100; i++)
p2.insert(i, new Integer(i));
for (int i = 0; i < 100; i++)
p3.insert(i, new Integer(i));
System.out.println("First insert tests");
System.out.print(p1.getPriority()+",");
while (!p1.empty()) {
p = p1.getPriority();
Object d = p1.getData();
p1.remove();
}
System.out.println(p);
System.out.print(p2.getPriority()+",");
while (!p2.empty()) {
p = p2.getPriority();
Object d = p2.getData();
p2.remove();
}
System.out.println(p);
System.out.print(p3.getPriority()+",");
while (!p3.empty()) {
p = p3.getPriority();
Object d = p3.getData();
p3.remove();
}
System.out.println(p);
System.out.println("First Remove Test");
for (int i = 100; i > 0 ; i--)
p1.insert(i, new Integer(i));
for (int i = 100; i > 0 ; i--)
p2.insert(i, new Integer(i));
for (int i = 100; i > 0 ; i--)
p3.insert(i, new Integer(i));
System.out.println("Second insert tests");
System.out.print(p1.getPriority()+",");
while (!p1.empty()) {
p = p1.getPriority();
Object d = p1.getData();
p1.remove();
}
System.out.println(p);
System.out.print(p2.getPriority()+",");
while (!p2.empty()) {
p = p2.getPriority();
Object d = p2.getData();
p2.remove();
}
System.out.println(p);
System.out.print(p3.getPriority()+",");
while (!p3.empty()) {
p = p3.getPriority();
Object d = p3.getData();
p3.remove();
}
System.out.println(p);
System.out.println("Second Remove Test");
Random r1 = new Random(1000);
while (!p3.full()) {
p = r1.nextInt(200);
System.out.print(p+",");
p3.insert(p, new Integer(p));
}
System.out.println();
while (!p3.empty()) {
System.out.print(p3.getPriority()+",");
Object d = p3.getData();
p3.remove();
}
System.out.println();
System.out.println("Third Remove Test");
}
}
Main includes 3 different ways I am testing my code.
If your problem is just with the findSmallest method, here is the solution:
public int findSmallest( int parent ) {
int smallestChild = -1;
int firstChild = parent * order + 1;
int lastChild = parent * order + order;
int currentSmallestChild = firstChild;
for ( int i = firstChild + 1; i <= lastChild; i++ ) {
if ( i > size || queue[i] == null ) {
break;
}
if ( queue[currentSmallestChild].priority > queue[i].priority ) {
currentSmallestChild = i;
smallestChild = i;
}
}
return smallestChild;
}
It will return -1 if there is not a smallest child. This code can be improved, I let it this way because I think it is easier to understand. Let me know if it works.

Java class method doesn't initialize

So I have a class assignment where the class I create implements an interface.
The main goals are to implement a new kind of queue that only accepts a single copy of an object in the queue,If an element is enqueued, and the element already exists in the queue, the queue will remain unchanged, and include a method moveToBack that allows you to de-prioritize an element in the queue.
I have several problems with my class that I am having troubles fixing.
1) there's an issue with my the NoDupes class inheriting from the Queue interface twice but when I try to fix by getting rid of the inheritance in the ArrayQueue class I can't get it to run
2) missing a loop that increments in moveToBack method but when I try fixing same issue as previous problem.
3)foundValue doesn't initialize
4)display(): should not print nulls when the queue is empty.
5) I don't know to implement enqueue().
The following is the classes I am implementing as my attempt, any help would be appreciated:
The ArrayQueue
public class ArrayQueue<T> implements QueueInterface<T> {
private T[] queue; // circular array of queue entries and one unused location
private int frontIndex;
private int backIndex;
private static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayQueue() {
this(DEFAULT_INITIAL_CAPACITY);
}
public ArrayQueue(int initialCapacity) {
queue = (T[]) new Object[initialCapacity + 1];
frontIndex = 0;
backIndex = initialCapacity;
}
public void enqueue(T newEntry) {
if (isArrayFull()) {
doubleArray();
}
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
}
public T getFront() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
}
return front;
}
public T dequeue() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
queue[frontIndex] = null;
frontIndex = (frontIndex + 1) % queue.length;
}
return front;
}
public boolean isEmpty() {
return frontIndex == ((backIndex + 1) % queue.length);
}
public void clear() {
if (!isEmpty()) { // deallocates only the used portion
for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length) {
queue[index] = null;
}
queue[backIndex] = null;
}
frontIndex = 0;
backIndex = queue.length - 1;
}
private boolean isArrayFull() {
return frontIndex == ((backIndex + 2) % queue.length);
}
private void doubleArray() {
T[] oldQueue = queue;
int oldSize = oldQueue.length;
queue = (T[]) new Object[2 * oldSize];
for (int index = 0; index < oldSize - 1; index++) {
queue[index] = oldQueue[frontIndex];
frontIndex = (frontIndex + 1) % oldSize;
}
frontIndex = 0;
backIndex = oldSize - 2;
}
}
public interface NoDupsDePrioritizeQueueInterface <T> extends
QueueInterface<T> {
/*
* Task: Moves the given entry to the back of the queue. If the entry is not
* in the queue, just add it at the end.
*
* #param entry the item to move or add
*/
public void moveToBack(T entry);
/*
* * Task: displays the contents of the queue (to be used for testing);
* specifies the front and back of the queue
*/
public void display();
}
public interface QueueInterface<T> {
public void enqueue(T newEntry);
/**
* Task: Removes and returns the entry at the front of the queue.
*
* #return either the object at the front of the queue or, if the queue is
* empty before the operation, null
*/
public T dequeue();
/**
* Task: Retrieves the entry at the front of the queue.
*
* #return either the object at the front of the queue or, if the queue is
* empty, null
*/
public T getFront();
/**
* Task: Detects whether the queue is empty.
*
* #return true if the queue is empty, or false otherwise
*/
public boolean isEmpty();
/** Task: Removes all entries from the queue. */
public void clear();
} // end QueueInterface
My implementation:
public class NoDupsDePrioritizeQueueInterface<T>
extends ArrayQueue
implements NoDupsDePrioritizeQueue<T> { //note, this was glitched before edit
public NoDupsDePrioritizeQueue() {
super();
}// end NoDupsDePrioritizeQueue
public NoDupsDePrioritizeQueue(int initialCapacity) {
super(initialCapacity)
}// end NoDupsDePrioritizeQueue
public void moveToBack(T newEntry) {
boolean found = false;
int start = frontIndex;
int back = backIndex;
int index = 0;
if (!isEmpty()) {
//searching if newEntry is already present in the queue. If it is present,
note its index. while (start != back) {
if (newEntry.equals(queue[start])) {
found = true;
index = start;
break;
}
start = (start + 1) % queue.length;
}
// the condition does not check queue[back] as the loop exits then.
//Hence we evaluate it separately.
if (newEntry.equals(queue[start])) {
found = true;
index = start;
}
//if its not found in the queue, do normal enqueue
if (found == false) {
enqueue(newEntry);
} else {
//shifting all elemets till the backindex and replacing the last element
//with the newEntry
foundValue = queue[index];
while ((index + 1) % queue.length <= backIndex) {
queue[index] = queue[(index + 1) % queue.length];
}
queue[backIndex] = foundValue;
}
} else {
enqueue(newEntry);
}
}
//end moveToBack
// displaying the queue without destroying it
public void display() {
int start = frontIndex;
int back = backIndex;
while (start != back && !isEmpty()) {
System.out.println(queue[start]);
start = (start + 1) % queue.length;
}
System.out.println(queue[start]);
}
}
The other part
/**
* A class that implements the ADT queue by using an expandable circular
* array
* with one unused location.
*/
public class ArrayQueue<T> {
protected T[] queue; // circular array of queue entries and one unused location
protected int frontIndex;
protected int backIndex;
protected static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayQueue() {
this(DEFAULT_INITIAL_CAPACITY);
}
public ArrayQueue(int initialCapacity) {
queue = (T[]) new Object[initialCapacity + 1];
frontIndex = 0;
backIndex = initialCapacity;
}
public void enqueue(T newEntry) {
//enqueue needs to be changed to eliminate duplicates
if (isArrayFull()) {
doubleArray();
}
boolean found = false;
//if its emtpy array, do normal enqueue operation
if (!isEmpty()) {
int start = frontIndex;
int back = backIndex;
//checking for duplicates by travelling through the array. however, we
//will miss queue[back] as the loop exits then.Hence we will search for it separately.
while (start != back) {
//if found, simply exit
if (newEntry.equals(queue[start])) {
found = true;
System.out.println("Element already exists");
return;
}
start = (start + 1) % queue.length;
}
if (newEntry.equals(queue[start])) {
found = true;
System.out.println("Element already exists");
return;
}
}
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
}
public T getFront() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
}
return front;
}
public T dequeue() {
T front = null;
if (!isEmpty()) {
front = queue[frontIndex];
queue[frontIndex] = null;
frontIndex = (frontIndex + 1) % queue.length;
}
return front;
}
public boolean isEmpty() {
return frontIndex == ((backIndex + 1) % queue.length);
}
public void clear() {
if (!isEmpty()) { // deallocates only the used portion
for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length) {
queue[index] = null;
}
queue[backIndex] = null;
}
frontIndex = 0;
backIndex = queue.length - 1;
}
private boolean isArrayFull() {
return frontIndex == ((backIndex + 2) % queue.length);
}
private void doubleArray() {
T[] oldQueue = queue;
int oldSize = oldQueue.length;
queue = (T[]) new Object[2 * oldSize];
for (int index = 0; index < oldSize - 1; index++) {
queue[index] = oldQueue[frontIndex];
frontIndex = (frontIndex + 1) % oldSize;
}
frontIndex = 0;
backIndex = oldSize - 2;
}
}
For your first question, the class declaration for NoDupsDePrioritizeQueue is just broken. I think you copied and pasted something wrong. Your wording implies that you somehow got this to run, which I completely disbelieve.
public class NoDupsDePrioritizeQueueInterface<T> extends ArrayQueue
NoDupsDePrioritizeQueue<T> implements {
This makes no sense. This is declaring a class which duplicates the name of your interface (which would never compile due to the name collision), has it extend another class and ... the second line is backwards/broken (which, again, would never compile). I think this should probably be
public class NoDupsDePrioritizeQueue<T> extends ArrayQueue
implements NoDupsDePrioritizeQueueInterface<T> {
This declares the class NoDupsDePrioritizeQueue, extending a class and implementing the interface.

Creating an Array Heap in Java

So i am trying to make an array based generic heap that i can use with my tester class. Much of what i have is based of my understandings of trees and some research online as well as from my textbook; both which have very limited info on what i am looking for. However, i did manage to get all the methods in need and when i run it, i get this error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at q1.Heaps.<init>(Heaps.java:23)
at q1.createGui.<init>(Gui.java:46)
at q1.Gui.main(Gui.java:18)
Im guessing it has to do with how i declare and initialize my Comparable array, which i am having trouble figuring out how to.
package q1;
import java.util.Arrays;
public class Heaps<E extends Comparable<E>> {
Comparable[] data;
int size;
/**
* Constructor with s as size
*/
#SuppressWarnings("unchecked")
public Heaps(int s) {
size = 0;
data = (E[]) new Object[s];
}
/**
* Adds a value to the heap
*/
public void add(E value) {
if (full()) // expand array
ensureCapacity(2*size);
size++;
data[size] = value;
if (size > 1)
heapifyUp();
}
/**
* Checks if the array is full
*/
private boolean full()
{
return (size == data.length-1);
}
private void heapifyUp()
{
Comparable<E> temp;
int next = size;
while (next != 1 && data[next].compareTo(data[next/2]) > 0)
{
temp = data[next];
data[next] = data[next/2];
data[next/2] = temp;
next = next/2;
}
}
private void heapifyDown()
{
Comparable<E> temp;
int next = 0;
while (next*2 <= size) // node has a child
{
int child = 2*next; // left child
if (child < size &&
data[child].compareTo(data[child+1]) > 0)//left smaller than right
child++; // right child instead
if (data[next].compareTo(data[child]) > 0)
{
temp = data[next];
data[next] = data[child];
data[child] = temp;
next = child;
}
else;
next = size; // stop loop
}//end while
}
/**
* Removes all occurrence of element
*/
public boolean removeAll(E element) {
if (contains(element) && !(isEmpty())){
for (int i = 0; i < size; i++){
if(element.equals(data[i])){
data[i] = data[size-1];
}
heapifyDown();
}
return true;
}
return false;
}
/**
* Removes 1st occurrence of element
*/
public boolean remove(E element) {
if (contains(element) && !(isEmpty())){
for (int i = 0; i < size; i++){
if(element.equals(data[i])){
data[i] = data[size-1];
heapifyDown();
return true;
}
}
}
return false;
}
public boolean isEmpty() {
return size == 0;
}
public Comparable<E>[] ensureCapacity(int s) {
return Arrays.copyOf(data, 2*s);
}
/**
* Converts the heap into its String representation.
* #return the String representation
*/
public Comparable<E>[] iteratorPreOrder()
{
Comparable<E>[] temp = (E[]) new Object[size];
temp[0] = data[0];
int i = 1;
int count = 1;
while(data[2*i] != null){
temp[count] = data[2*i];
++i;
++count;
}
i = 1;
while(data[(2*i) +1] != null){
temp[count] = data[(2*i) +1];
++i;
++count;
}
return temp;
}
public int countOccurance(E element){
int count = 0;
for (int i =0; i < size; i++){
if(element.equals(data[i])){
count++;
}
}
return count;
}
public boolean contains (E element)
{
for (int i=0; i<size; i++){
if (element.equals(data[i])){
return true;
}
}
return false;
}
}
If you could please show me how i would solve this problem, i would greatly appreciate it. Thanks
EDIT: SO i edited the my class and now it works when i do data = (E[]) new Comparable[s]. So why does java not allow generic Array types, what makes it different from Arraylist, Stacks, Queues, and/or LinkedList which can be generic?
You are creating an Object[] and then trying to cast it to a Comprable[]. The compiler was telling you what you did wrong with the unchecked cast error.
You want data to be E[] data and the line to be:
data = new E[s];
Note: this could run into issues with how Java handles generics.

Program won't compile completely without giving an error of parsing

I'm writing this code to implement a stack as a linked list but I keep getting an error when I compile this part of the code and can't figure out why
I definitely know that it shouldn't be giving me this error since there are enough brackets and none of them are out of place I hope
The Error:
C:\Users\Michelle\Desktop\ITB\Semester 5\Data Structures & Algorithms\Assignment\ListReference.java:108: error: reached end of file while parsing
}
^
1 error
My Code:
public class ListReference implements StackInterface {
private Node top;
//private Object item;
private int NumItems;
public ListReference() {
NumItems = 0;
top = new Node(null);
}
public boolean isEmpty() {
return NumItems == 0;
}
public int size() {
return NumItems;
}
/*public Node find(int index) {
Node curr = tail;
for(int skip = 1; skip < index; skip++) {
curr.getNext();
}
return curr;
}*/
public Object get(int index) {
if(index <= 0)
return null;
Node ListReference = top.getNext();
for(int i=1; i < index; i++) {
if (ListReference.getNext() == null)
return null;
ListReference = ListReference.getData();
}
}
public void add(int index, Object item) {
Node ListReferenceTemp = new Node(item);
Node ListRefCurr = top;
while(ListRefCurr.getNext() != null) {
ListRefCurr = ListRefCurr.getNext();
}
ListRefCurr.setNext(ListReferenceTemp);
NumItems++;
}
public void add(Object data) {
Node ListReferenceTemp = new Node(item);
Node ListRefernce = top;
for(int i=1; i < index && ListReference.getNext() != null; i++) {
ListReference = ListReference.getNext();
}
ListReferenceTemp.setNext(ListReference.getNext());
ListReference.setNext(ListReferenceTemp);
NumItems++;
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node ListRefCurr = top;
for (int i = 1; i < index; i++) {
if (ListRefCurr.getNext() == null) {
return false;
}
ListRefCurr = ListRefCurr.getNext();
}
ListRefCurr.setNext(ListRefCurr.getNext().getNext());
NumItems--; // decrement the number of elements variable
return true;
}
public String toString() {
Node ListReference = top.getNext();
String output = "";
while (ListREference != null) {
output += "[" + ListRefCurr.getData().toString() + "]";
ListRefCurr = ListRefCurr.getNext();
}
return output;
}

Categories

Resources