How to display all elements in a Prefix tree? - java

I'm trying to print all the word in my prefix tree. I can insert, it's working, but when I try to print all elements of the tree using a preorder way it just gets all messed up. There's some problem on the recursive method PREORDER that I'm using to display all elements.
How can I recursively display all the word on my prefix tree???
public class TrieMain {
public static void main(String[] args) {
TrieTree tree = new TrieTree();
tree.treeInsert("cat");
tree.treeInsert("cattle");
tree.treeInsert("hell");
tree.treeInsert("hello");
tree.treeInsert("rip");
tree.treeInsert("rap");
tree.preorder(tree.getRoot(), "");
}
}
public class TrieTree {
private TrieNode root;
private int wordCount;
public TrieTree() {
this.root = null;
this.wordCount = 0;
}
public TrieNode getRoot() {
return this.root;
}
public void setRoot(TrieNode newRoot) {
this.root = newRoot;
}
public int getWordCount() {
return this.wordCount;
}
public void preorder(TrieNode root, String prefix) {
if (root.getTerminal()) {
System.out.println(prefix);
}
for (int i = 0; i < 26; i++) {
if (root.getCharacters()[i] != '\u0000') {
prefix += root.getCharacters()[i];
preorder(root.getPointers()[i], prefix);
}
}
}
public boolean treeInsert(String word) {
if (this.root == null) {
this.root = new TrieNode();
}
TrieNode temp;
temp = this.root;
int lengthWord = word.length();
for (int i = 0; i < lengthWord; i++) {
int index = getIndex(word.charAt(i));
if (temp.getCharacters()[index] == '\u0000') {
temp.getCharacters()[index] = word.charAt(i);
temp.getPointers()[index] = new TrieNode();
}
temp = temp.getPointers()[index];
}
if (temp.getTerminal()) {
return false;
}
else {
temp.setTerminal(true);
return true;
}
}
public int getIndex(char character) {
int index = ((int) character) - 97;
return index;
}
}
public class TrieNode {
private final int NUM_CHARS = 26;
private char[] characters;
private TrieNode[] pointers;
private boolean terminal;
public TrieNode() {
this.characters = new char[this.NUM_CHARS];
this.pointers = new TrieNode[this.NUM_CHARS];
for (int i = 0; i < this.NUM_CHARS; i++) {
this.characters[i] = '\u0000';
this.pointers[i] = null;
}
this.terminal = false;
}
public char[] getCharacters() {
return this.characters;
}
public TrieNode[] getPointers() {
return this.pointers;
}
public boolean getTerminal() {
return this.terminal;
}
public void setTerminal(boolean newTerminal) {
this.terminal = newTerminal;
}
}

Related

TreeSet wont add edges

i have to code the Dijkstra algorithm. We got a blueprint for this project. Meaning we were told the classes, field variables and methods we have to use.
We have to read the adjacency matrix from a csv file and then use the Dijkstra algorithm.
My problem already begins in in filling the TreeSet edges...
The problem occurs in Graph.class on line 45 when i try to add the Edges.
Example for the csv :
;A;B;C;D;E;F;G;H
A;;1;3;1;;;;
B;1;;;;3;3;;
C;3;;;1;;;1;
D;1;;1;;1;;2;
E;;3;;1;;1;;5
F;;3;;;1;;;1
G;;;1;2;;;;1
H;;;;;5;1;1;
=>
A -> (B,1), (C,3), (D,1)
B -> (A,1), (E,3), (F,3)
C -> (A,3), (D,1), (G,1)
D -> (A,1), (C,1), (E,1), (G,2)
E -> (B,3), (D,1), (F,1), (H,5)
F -> (B,3), (E,1), (H,1)
G -> (C,1), (D,2), (H,1)
H -> (E,5), (F,1), (G,1)
Could somebody look where my problem is ? My indices are correct i checked them with some sout.
Just need help with filling in the TreeSet! I want to try the Dijkstra part myself.
public class Edge implements Comparable<Edge>{
private int distance;
private Node neighbour;
public Edge(int distance, Node neighbour) {
this.distance = distance;
this.neighbour = neighbour;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public Node getNeighbour() {
return neighbour;
}
public void setNeighbour(Node neighbour) {
this.neighbour = neighbour;
}
#Override
public int compareTo(Edge o) {
if (this.neighbour.getId().equals(o.neighbour.getId())){
return 0;
}else{
return -1;
}
}
}
import java.util.TreeSet;
public class Node {
private String id;
private TreeSet<Edge> edges;
private int distance;
private Node previous;
private boolean isVisited;
public Node(String id) {
this.id = id;
this.edges = new TreeSet<>();
}
public Node(String id, int distance){
this.id = id;
this.distance = distance;
}
#Override
public String toString() {
return "Node{" +
"id='" + id + '\'' +
", edges=" + edges +
", distance=" + distance +
", previous=" + previous +
", isVisited=" + isVisited +
'}';
}
public String getPath(){
return null;
}
public void addEdge(Edge e){
edges.add(e);
}
public void init(){
}
public void setStartNode(Node n){
}
public void visit(Node n){
}
public String getId() {
return id;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.util.*;
public class Graph {
private PriorityQueue pq;
private ArrayList<Node> nodes;
public Graph(){
this.pq = new PriorityQueue();
this.nodes = new ArrayList();
}
public void readGraphFromAdjacencyMatrixFile(Path file) throws FileNotFoundException {
Scanner sc = new Scanner(new File(String.valueOf(file)));
ArrayList<String> s = new ArrayList<>();
ArrayList<Character> nodesCharacter = new ArrayList<Character>();
while (sc.hasNext()){
s.add(sc.next());
}
sc.close();
for(char ch: s.get(0).toCharArray()){
if (ch != ';' && ch != ',') {
nodes.add(new Node(Character.toString(ch)));
nodesCharacter.add(ch);
}
}
ArrayList<Node> nodes2 = getNodes();
String node = "";
int index = 0;
for (int i = 1; i < s.size(); i++){
int cnt = -2;
char[] chArray = s.get(i).toCharArray();
for (int j = 0; j < chArray.length; j++){
if(j == 0){
node = String.valueOf(chArray[j]);
index = indexOfNode(String.valueOf((chArray[j])));
}
else if (j >= 2){
if (Character.isDigit(chArray[j])){
int neighbourIndex = indexOfNode("" + nodesCharacter.get(cnt));
Edge e = new Edge(Character.getNumericValue(chArray[j]), nodes.get(neighbourIndex));
nodes.get(index).addEdge(e);
cnt--;
}
}
cnt ++;
}
}
}
public String getAllPAths(){
return null;
}
public void calcWithDijkstra(String startNodeId){
}
public ArrayList<Node> getNodes() {
return nodes;
}
public int indexOfNode(String id){
int cnt = 0;
for (int i = 0; i < nodes.size(); i++){
if (id.equals(nodes.get(i).getId())){
return cnt;
}
cnt++;
}
return -1;
}
}

Can I add elements to a java queue using array without defining the front and the rear? I am having trouble with this

I am having trouble using enqueue and dequeue functions. I want to add elements without defining the front and rear in my scope.
public class MyStaticQueue
{
private int items[] ;
private int noOfItems = 0;
private int maxItems;
public MyStaticQueue(int m)
{
this.maxItems = m;
this.items = new int[maxItems];
this.noOfItems = 0;
}
public boolean isEmpty()
{
if(noOfItems == 0)
{
return true;
}
else
{
return false;
}
}
public int first()
{
return items[0];
}
public void add(int item)
{
for (int i=0; i<items[maxItems]; i++)
{
if (items[i] == 0)
{
items[i] = item;
}
noOfItems++;
}
}
}

How do I test delete() in the class growingArray

I'm learning the Growing Array in Java, and I implemented the method delete() in the following Code.
Now I want to test this method for a example array [1,2,3,4,5,6,7]
What do I have to write in the Main method?
import java.util.Arrays;
public abstract class GrowingArray {
protected Object[] array;
protected static final int primaryQty = 10;
protected static final int secondaryQty = 5;
protected int index = 0;
public GrowingArray() {
array = new Object[primaryQty];
}
public GrowingArray(int size) {
array = new Object[size];
}
protected void grow() {
int oldsize = array.length;
int newsize = oldsize + secondaryQty;
Object[] loc = new Object[newsize];
for (int i = 0; i < oldsize; i++)
loc[i] = array[i];
array = loc;
}
public Object get(int at) {
return array[at];
}
public int getLength() {
return array.length;
}
public void add(Object obj) {
if (index < array.length)
array[index++] = obj;
else {
grow();
array[index++] = obj;
}
}
public void delete(int x) {
for (int i = x; i < array.length; i++) {
if (i == array.length - 1) {
array[i] = null;
System.out.println(array.toString());
} else {
array[i] = array[i + 1];
System.out.println(array.toString());
}
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GrowingArray) {
return Arrays.equals(array, ((GrowingArray) obj).array);
}
return false;
}
#Override
public String toString() {
return Arrays.toString(array);
}
public static void main(String args[]) {
//test ?????
}
}
Your class is abstract. Remove abstract from the class definition.

Why will my program not go into my while loop?

I'm working on a program that will take a name and number of a periodic element, store it in a tree and then print it out in different orders.
When I try and run my main class it asks for the name, but then it doesn't go into the while loop.
Here is my main class.
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name;
int atomicNum;
BSTInterface<PeriodicElement> elements = new BSTree<PeriodicElement>();
PeriodicElement element;
int numElements;
String skip;
System.out.print("Element name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""));
{
System.out.print("Atomic Number: ");
atomicNum = conIn.nextInt();
skip = conIn.nextLine();
element = new PeriodicElement(name, atomicNum);
elements.add(element);
System.out.print("Element name (press ENTER TO END): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("Periodic Elements");
numElements = elements.reset(BSTree.INORDER);
for (int count = 1; count <= numElements; count++)
{
System.out.println(elements.getNext(BSTree.INORDER));
}
}
}
Here is my Binary Search Tree
public class BSTree <T extends Comparable<T>>
implements BSTInterface<T>
{
protected BSTNode<T> root;
boolean found;
protected LinkedUnbndQueue<T> inOrderQueue;
protected LinkedUnbndQueue<T> preOrderQueue;
protected LinkedUnbndQueue<T> postOrderQueue;
public BSTree()
{
root = null;
}
public boolean isEmpty()
{
return (root == null);
}
private int recSize(BSTNode<T> tree)
{
if(tree == null)
{
return 0;
}
else
{
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
}
public int size()
{
int count = 0;
{
if(root != null)
{
LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>();
BSTNode<T> currNode;
hold.push(root);
while(!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if(currNode.getLeft() != null)
{
hold.push(currNode.getLeft());
}
if(currNode.getRight() != null)
{
hold.push(currNode.getRight());
}
}
}
//System.out.println(count);
return count;
}
}
public boolean recContains(T element, BSTNode<T> tree)
{
if(tree == null)
{
return false;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recContains(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recContains(element, tree.getRight());
}
else
{
return true;
}
}
public boolean contains (T element)
{
//System.out.println("Tree contains: " + recContains(element, root));
return recContains(element, root);
}
public T recGet(T element, BSTNode<T> tree)
{
if(tree == null)
{
return null;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recGet(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recGet(element, tree.getRight());
}
else
{
return tree.getInfo();
}
}
public T get(T element)
{
//System.out.println(recGet(element, root));
return recGet(element, root);
}
public void add(T element)
{
root = recAdd(element, root);
}
private BSTNode<T> recAdd(T element, BSTNode<T> tree)
{
if(tree == null)
{
tree = new BSTNode<T>(element);
}
else if(element.compareTo(tree.getInfo()) <= 0)
{
tree.setLeft(recAdd(element, tree.getLeft()));
}
else
{
tree.setRight(recAdd(element, tree.getRight()));
}
return tree;
}
public boolean remove(T element)
{
root = recRemove(element, root);
return found;
}
private BSTNode<T> recRemove(T element, BSTNode<T> tree)
{
if(tree == null)
{
found = false;
}
else if (element.compareTo(tree.getInfo()) < 0)
{
tree.setLeft(recRemove(element, tree.getLeft()));
}
else if (element.compareTo(tree.getInfo()) > 0)
{
tree.setRight(recRemove(element, tree.getRight()));
}
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
private BSTNode<T> removeNode(BSTNode<T> tree)
{
T data;
if(tree.getLeft() == null)
{
return tree.getRight();
}
else if(tree.getRight() == null)
{
return tree.getLeft();
}
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private T getPredecessor(BSTNode<T> tree)
{
while (tree.getRight() != null)
{
tree = tree.getRight();
}
return tree.getInfo();
}
public int reset(int orderType)
{
int numNodes = size();
if(orderType == INORDER)
{
inOrderQueue = new LinkedUnbndQueue<T>(numNodes);
}
else
{
if(orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue<T>(numNodes);
preOrder(root);
}
if(orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue<T>(numNodes);
postOrder(root);
}
}
return numNodes;
}
public T getNext(int orderType)
{
if(orderType == INORDER)
{
return inOrderQueue.dequeue();
}
else
{
if(orderType == PREORDER)
{
return preOrderQueue.dequeue();
}
else
{
if(orderType == POSTORDER)
{
return postOrderQueue.dequeue();
}
else
{
return null;
}
}
}
}
private void inOrder(BSTNode<T> tree)
{
if(tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode<T> tree)
{
if(tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode<T> tree)
{
if(tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
}
Here is the Binary Search Tree Node class
public class BSTNode <T extends Comparable<T>>
{
protected T info;
protected BSTNode<T> left;
protected BSTNode<T> right;
public BSTNode(T info)
{
this.info = info;
left = null;
right = null;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return info;
}
public void setLeft(BSTNode<T> link)
{
left = link;
}
public void setRight(BSTNode<T> link)
{
right = link;
}
public BSTNode<T> getLeft()
{
return left;
}
public BSTNode<T> getRight()
{
return right;
}
}
Remove the semi-colon that is terminating the while statement
while (!name.equals(""));
^
Remove the semi colon after the while statment because a semi colon makes it end there while a { is the start if while something is true or not (!) and it should end as you obviously know with a }.

Java Hashtable Chaining

I am supposed to write a Java Hashtable function being able to import java.util.Iterator, java.util.NoSuchElementException, and java.util.ConcurrentModificationException. There is no specific on what type of Hashing function to use. SO how do I write my getHashCode function. My code so far:
package data_structures;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import data_structures.LinkedListDS.IteratorHelper;
public class Hashtable<K,V> implements DictionaryADT<K,V> {
private int currentSize,maxSize,tableSize;
private long modCounter;
private LinkedListDS <DictionaryNode<K,V>> [] list;
class DictionaryNode<K,V> implements Comparable<DictionaryNode<K,V>> {
K key;
V value;
public DictionaryNode(K k, V v) {
key = k;
value = v;
}
public int compareTo(DictionaryNode<K,V> node) {
return ((Comparable<K>)key).compareTo((K)node.key);
}
}
public Hashtable(int n) {
currentSize = 0;
maxSize = n;
modCounter = 0;
tableSize = (int) (maxSize * 1.3f);
list = new LinkedListDS[tableSize];
for (int i=0; i < tableSize; i++)
list[i] = new LinkedListDS<DictionaryNode<K,V>>();
}
public boolean contains(K key) {
return list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null));
}
private int getHashCode(K key) {
// TODO Auto-generated method stub
return 0;
}
public boolean insert(K key, V value) {
if (isFull())
return false;
if (list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].addLast(new DictionaryNode<K,V>(key,value));
currentSize++;
modCounter++;
return true;
}
#Override
public boolean remove(K key) {
if (isEmpty())
return false;
if (!list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].remove(new DictionaryNode<K,V>(key,null));
currentSize--;
modCounter++;
return true;
}
public V getValue(K key) {
DictionaryNode<K,V> tmp = list[getHashCode(key)].find(new DictionaryNode<K,V>(key,null));
if (tmp == null)
return null;
return tmp.value;
}
#Override
public K getKey(V value) {
DictionaryNode<K,V> tmp = list[getHashCode(value)].find(new DictionaryNode<K,V>(null,value));
if (tmp == null)
return null;
return tmp.key;
}
public int size() {
return currentSize;
}
#Override
public boolean isFull() {
return currentSize == maxSize;
}
public boolean isEmpty() {
return currentSize == 0;
}
#Override
public void clear() {
currentSize = 0;
modCounter++;
for (int i=0; i<tableSize; i++)
list[i].makeEmpty();
}
public Iterator<K> keys() {
return new KeyIteratorHelper();
}
public Iterator<V> values() {
return new ValueIteratorHelper();
}
abstract class IteratorHelper<E> implements Iterator<E> {
protected DictionaryNode<K,V> [] nodes;
protected int idx;
protected long modCheck;
public IteratorHelper() {
nodes = new DictionaryNode[currentSize];
idx = 0;
int j = 0;
for (int i=0; i < tableSize; i++)
for (DictionaryNode n : list[i])
nodes[j++] = n;
nodes = (DictionaryNode<K,V>[]) ObjectSorter.quickSort(nodes);
}
public boolean hasNext() {
if (modCheck != modCounter)
throw new ConcurrentModificationException();
return idx < currentSize;
}
public abstract E next();
public void remove() {
throw new UnsupportedOperationException();
}
}
class KeyIteratorHelper<K> extends IteratorHelper<K> {
public KeyIteratorHelper() {
super();
}
public K next() {
return (K) nodes[idx++].key;
}
}
class ValueIteratorHelper<V> extends IteratorHelper<V> {
public ValueIteratorHelper() {
super();
}
public V next() {
return (V) nodes[idx++].value;
}
}
}

Categories