Creating a BST with each node having a key and name - java

I have been tasked to you use the names and surnames in
toSearchIn.txt
in order
to tally and
print out,
the popularity of each of the names and
surnames in Bob’s friend list
.
Maintain two separate BSTs (one for names and one for surnames).
A node in the name BST stores a name, a counter for the num
ber of occurrences of that name, a key ( sum of chars of the name) and references to its left and right children
.
A node in the surname BST stores a surname, a counter for the number of occurrences of that
surname, a key (sum of chars
of the surname) and references to its left and right children.
Output
:
Traverse the name tree in order to print out each key, name and the number of occurrences of that name. Traverse the surname tree post order in order to print out the key, surname and the number of occurrences of that surname.
So i got 3 classes and my code is supposed to print all the names, their keys and popularity but it only prints 4 names.
Can anyone help me out??
here are my classes:
import java.util.*;
import java.io.*;
public class BSTMain{
public static ArrayList<String> names;
public static ArrayList<String> surNames;
public static ArrayList<Integer> keys;
public static ArrayList<Integer> keysNames;
public static ArrayList<Integer> keysSurnames;
public static void main(String args[]){
keysNames = new ArrayList<Integer>();
keysSurnames = new ArrayList<Integer>();
BSTMethods treeName = new BSTMethods();
BSTMethods treeSurname = new BSTMethods();
BSTNode node = new BSTNode();
names = new ArrayList<String>();
surNames = new ArrayList<String>();
//open textfiel and read names
try {
BufferedReader reader = new BufferedReader(new FileReader("toSearchIn.txt"));
//iterate through the textfile to read fullnames
while((reader.readLine()) != null){
String fullName = reader.readLine();
//string becomes an array of 2 elements
String[] array_fullName = new String[2];
if(fullName != null)
array_fullName = fullName.split(" ");
else break;
//first element in array is the name
String name = array_fullName[0];
//adding the name to the array of names
names.add(name);
//2nd element in array becomes the surname
String surname = array_fullName[1];
//adding the surname to the array of surnames
surNames.add(surname);
}
}
//File not a textfile
catch (Exception e) {
e.printStackTrace();
}
keysNames = BSTMethods.computeKey(names);
keysSurnames = BSTMethods.computeKey(surNames);
for(int i =0; i <(names.size()); i++) {
treeName.addNode(keysNames.get(i), names.get(i));
// System.out.println( names.get(i) );
treeSurname.addNode(keysSurnames.get(i), surNames.get(i));
// System.out.println( surNames.get(i) );
}
System.out.println("Name BST Traversed In Order");
treeName.inOrder(treeName.root);
System.out.println("**************************************************************\n");
System.out.println("Surname BST Traversed Post Order");
treeSurname.postOrder(treeSurname.root);
}
}
import java.util.*;
import java.io.*;
public class BSTMethods{
private static ArrayList<String> names;
private static ArrayList<String> surNames;
private static ArrayList<Integer> keys = new ArrayList<Integer>();
public BSTNode root;
public BSTNode parent;
public BSTNode current;
public BSTNode temp = root;
BSTNode counter = new BSTNode();
//keys ;
//adding keys method for names
public static ArrayList<Integer> computeKey(ArrayList<String> names){
int sum = 0;
int char1 = 0;
//determining keys for names and surnames
for(int i = 0; i < names.size(); i++){
//for each string name, process its characters and
//work out int values
for(int j = 1; j < (names.get(i)).length(); j++){
//char at position 0
char1 = (int)(names.get(i)).charAt(0);
//summing the character int values
sum = (char1) + (int)(names.get(i)).charAt(j);
}
//and add to the keys' list
keys.add(sum);
//resetting sum
sum = 0;
}
return keys;
}
public boolean addNode(int key, String name) {
if(root == null) {
root = new BSTNode(key, name);
temp = root;
return true;
}
else if (key == temp.key){
temp.setCount();
return false;
}
else if (key <temp.key) {
if(temp.left == null){
temp.left = new BSTNode(key, name);
return true;
}
else {
temp = temp.left;
return addNode(key, name);
}
}
else if (key > temp.key) {
if (temp.right == null) {
temp.right = new BSTNode(key, name);
return true;
}
else
return true;//addNode(key, name);
}
else
return false;
}
public void inOrder (BSTNode x) {
if(x == null) return ;
if(x.left != null){
inOrder(x.left);
}
System.out.println("key:"+ x.key + ", name:" + x.name + ", count:" + temp.count );
if(x.right != null){
inOrder(x.right);
}
}
public void postOrder (BSTNode y) {
if(y.left != null){
postOrder(y.left);
}
if(y.right != null){
postOrder(y.right);
}
System.out.println("key:"+ y.key + ", surname:" + y.name + ", count:" + counter.getCount());
}
}
import java.util.*;
import java.io.*;
public class BSTNode{
public int count, key;
public String name, surname;
public BSTNode left;
public BSTNode right;
public BSTNode()
{
this.left = null;
this.right = null;
}
public BSTNode(int key, String name) {
this.key = key;
this.name = name;
}
public void setCount()
{
count += 1;
}
public int getCount()
{
return this.count;
}
public BSTNode getLeft()
{
return left;
}
public void setLeft(BSTNode left)
{
this.left = left;
}
public BSTNode getRight()
{
return right;
}
public void setRight(BSTNode right)
{
this.right = right;
}
}

Related

How to read from a file and stored data in a linked lists

I am trying to read from a file and store the data into a single linked lists.
The data should have information about a user including id of type long, name of type string, and threat level of type int. Moreover, I am wondering how to read from the file and store into the linked list so that I can then do several operations.
my attempt:
class POI
public class POI {
private long id;
private String name;
private int level;
public POI(){
}
public POI(long n, String s, int l){
id = n;
name = s;
level = l;
}
public void setID (long n){
id = n;
}
public void setName (String s){
name = s;
}
public void setLevel (int l){
level = l;
}
public long getID(){
return id;
}
public String getName(){
return name;
}
public int getLevel(){
return level;
}
}
class POIList
public class POIList {
static private class Node {
int data;
Node next;
Node () {
data = 0;
next = null;
}
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
public static void print(Node head) {
while (head != null) {
System.out.print(head.data + ", ");
head = head.next;
}
System.out.println();
}
public Node insertNode(Node head, Node insertee, int position) {
if (position < 0) {
System.out.println("Invalid position given");
return head;
}
if (head == null) {
return insertee;
}
if (position == 0) {
insertee.next = head;
return insertee;
}
int i = 0;
Node current=head;
while (i < position - 1 && current.next != null) {
current = current.next;
i++;
}
if (i == position - 1) {
insertee.next = current.next;
current.next = insertee;
} else {
System.out.println("Position was not found.");
}
return head;
}
static Node swapNode(Node head,
int position1, int position2) {
if(position1 < 0 || position2 < 0)
System.out.println("InvalidPos");
Node n1 = null;
Node n2 = null;
Node prev1=null;
Node prev2=null;
int maxPosition = Math.max(position1, position2);
if (position1==maxPosition){
position1=position2;
position2=maxPosition;
}
Node temp=head;
for (int i = 0;i <= maxPosition; i++) {
if (temp == null) {
System.out.println("InvalidPos");
return head;
}
if (i==position1-1) prev1=temp;
if(i == position1) n1 = temp;
if (i==position2-1) prev2=temp;
if(i == position2) n2 = temp;
temp = temp.next;
}
temp = n2.next;
if (prev1!=null){
prev1.next=n2;
}else{
head=n2;
}
if (position2-position1==1){
n2.next=n1;
}else{
n2.next=n1.next;
}
if (prev2!=null){
prev2.next=n1;
}else{
head=n1;
}
n1.next=temp;
return head;
} // End of swapNode
public static Node removeNode(Node head, int position) {
if (position < 0 || head == null) {
System.out.println("Invalid position given");
return head;
}
if (position == 0) {
return head.next;
}
int i = 0;
Node current = head;
while (i < position - 1 && current.next != null) {
current = current.next;
i++;
}
if (current.next != null) {
current.next = current.next.next;
} else {
System.out.println("Position was not found.");
}
return head;
}
}
class AnalyzePOI
public class AnalyzePOI {
public static void main (String [] args) throws FileNotFoundException, IOException{
Scanner scan = new Scanner(System.in);
int choice;
System.out.print("Input filename:");
String filename = scan.nextLine();
File file = new File(filename);
Scanner reader = new Scanner(file);
POIList list = new POIList();
System.out.println("What operation would you like to implement? ");
choice = scan.nextInt();
switch (choice) {
case 1 : print(list) ;
break ;
case 2 : search(reader, list) ;
break ;
case 3 : insert(scan, list);
break ;
case 4 : swap(reader, list);
break ;
case 5 : remove1(reader, list);
break;
case 6 : remove2(reader, list);
break;
case 7 : output();
break;
case 8 :
System.out.println ("Program Terminated");
System.exit(0);
break;
}
start(scan,file, reader );
}
public static void start (Scanner scan, File file, Scanner reader){
String content = new String();
int count=1;
File file1 = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
}catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
Collections.reverse(list);
Iterator i = (Iterator) list.iterator();
while (((java.util.Iterator<String>) i).hasNext()) {
System.out.print("Node " + (count++) + " : ");
System.out.println();
}
}
public static void print(POIList list) {
list.print(null);
}
public static void search(Scanner scan, POIList list) {
int id;
String name;
System.out.println("Do you want to enter id or name to search for record: ");
String answer = scan.next();
if (answer == "id"){
System.out.println ("Enter the id to find the record: ");
id = scan.nextInt();
}
else if (answer == "name"){
System.out.println("Enter the name to find the record: ");
name = scan.nextLine();
}
else{
System.out.println("Invalid input");
}
}
public static void insert(Scanner scan, POIList list) {
System.out.println("Enter the the location index ");
int index = 0;
long p1;
int level;
String name;
try {
System.out.println("Index: ") ;
index= scan.nextInt() ;
System.out.println("ID: ") ;
p1=scan.nextLong() ;
System.out.println("Name: ");
name = scan.nextLine();
System.out.println("Threat Level ") ;
level=scan.nextInt() ;
}
catch (InputMismatchException e) {
System.out.print("Invalid Input") ;
}
list.insertNode(null, null, index);
}
public static void swap(Scanner scan, POIList list) {
System.out.println("Enter index 1 to swap record: ");
int index1 = scan.nextInt();
System.out.println("Enter index 2 to swap record: ");
int index2 = scan.nextInt();
list.swapNode(null, index1, index2);
}
public static void remove1(Scanner scan, POIList list) {
int index= 0;
try{
System.out.println("Enter ID to remove a record: ") ;
index=scan.nextInt() ;
}
catch (InputMismatchException e) {
System.out.print("Invalid Input") ;
}
list.removeNode(null, index) ;
}
public static void remove2(Scanner scan, POIList list){
int index = 0;
try{
System.out.println("Enter threat level to remove a record: ");
index=scan.nextInt() ;
}
catch (InputMismatchException e){
System.out.println("Invalid Input");
}
list.removeNode(null, index) ;
}
public static void output() {
}
}
Assuming from your question, you would like to know how to read the file that contains "String" "long" and an "int" value. Let's suppose your input file would look like this as given below.
First, we need to know how the data would look like. I'm assuming that the I/P would look something like this
1 OneString 10
2 TwoSTring 20
Now, the order I'm assuming is "long" "String" "int" with a space in between for each line. Use bufferedReader for faster reading.
FileReader fr = new FileReader("yourFile.txt");
BufferedReader br = new BufferedReader(fr);
String curLine = br.next();
while(curLine!=null)
{
String[] tempLine = curLine.split(" ");
int threat = Integer.parseInt(tempLine[0]);
String user = tempLine[1];
long ID = Long.parseLong(tempLine[2]);
addPOI(ID,user,threat);
}
The addPOI method would look something like this.
public void addPOI(long ID, String user, int threatLevel)
{
list.addAtLast(new POI(ID,user,threadLevel));
}
And the list can be declared something like this,
List<POI> list = new List<POI>();

AutoComplete using a Trie in Java

I am working on this assignment which implements Autocomplete and dictionary. I have sucessfully implemented spellcheck and the addWord() and isWord() functions.
But I am just not able to implement the function which predicts words for AutoCompletions.
package spelling;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
/**
* An trie data structure that implements the Dictionary and the AutoComplete ADT
* #author You
*
*/
public class AutoCompleteDictionaryTrie implements Dictionary, AutoComplete {
private TrieNode root;
private int size;
public AutoCompleteDictionaryTrie()
{
root = new TrieNode();
size=0;
}
/** Insert a word into the trie.
* For the basic part of the assignment (part 2), you should ignore the word's case.
* That is, you should convert the string to all lower case as you insert it. */
public boolean addWord(String word)
{
//TODO: Implement this method.
String Word=word.toLowerCase();
if(isWord(Word))
return false;
HashMap<Character, TrieNode> children=root.children;
for(int i=0; i<Word.length(); i++){
char c = Word.charAt(i);
TrieNode t;
if(children.containsKey(c)){
t = children.get(c);
}else{
t = new TrieNode(""+(c));
children.put(c, t);
}
children = t.children;
if(i==Word.length()-1)
{
t.isWord = true;
size++;
}
}
return true;
}
/**
* Return the number of words in the dictionary. This is NOT necessarily the same
* as the number of TrieNodes in the trie.
*/
public int size()
{
//TODO: Implement this method
return size;
}
/** Returns whether the string is a word in the trie */
#Override
public boolean isWord(String s)
{
// TODO: Implement this method
TrieNode t = searchNode(s.toLowerCase());
if(t != null && t.isWord)
return true;
else
return false;
}
public TrieNode searchNode(String str){
HashMap<Character, TrieNode> children = root.children;
TrieNode t = null;
for(int i=0; i<str.length(); i++){
char c = str.charAt(i);
if(children.containsKey(c)){
t = children.get(c);
children = t.children;
}else{
return null;
}
}
return t;
}
/**
* * Returns up to the n "best" predictions, including the word itself,
* in terms of length
* If this string is not in the trie, it returns null.
* #param text The text to use at the word stem
* #param n The maximum number of predictions desired.
* #return A list containing the up to n best predictions
*/#Override
public List<String> predictCompletions(String prefix, int numCompletions)
{
// TODO: Implement this method
// This method should implement the following algorithm:
// 1. Find the stem in the trie. If the stem does not appear in the trie, return an
// empty list
// 2. Once the stem is found, perform a breadth first search to generate completions
// using the following algorithm:
// Create a queue (LinkedList) and add the node that completes the stem to the back
// of the list.
// Create a list of completions to return (initially empty)
// While the queue is not empty and you don't have enough completions:
// remove the first Node from the queue
// If it is a word, add it to the completions list
// Add all of its child nodes to the back of the queue
// Return the list of completions
List<String> completions=null;
int counter=0;
if (prefix==null){
return Collections.emptyList();
}
prefix=prefix.toLowerCase();
if(isWord(prefix))
completions.add(prefix);
LinkedList nodes = new LinkedList();
TrieNode curr=searchNode(prefix);
nodes.addLast(curr);
while(!nodes.isEmpty() && counter!=numCompletions)
{
if((nodes.removeFirst()).isWord)
completions.add(curr.getText());
TrieNode next = null;
for (Character c : curr.getValidNextCharacters()) {
next = curr.getChild(c);
}
}
return Collections.emptyList();
}
public void checkNull(String word){
if (word==null)
throw new NullPointerException("Null word passed");
}
// For debugging
public void printTree()
{
printNode(root);
}
/** Do a pre-order traversal from this node down */
public void printNode(TrieNode curr)
{
if (curr == null)
return;
System.out.println(curr.getText());
TrieNode next = null;
for (Character c : curr.getValidNextCharacters()) {
next = curr.getChild(c);
printNode(next);
}
}
}
And this is the code of the TrieNode class:
package spelling;
import java.util.HashMap;
import java.util.Set;
/**
* Represents a node in a Trie
* #author UC San Diego Intermediate Programming MOOC Team
*
*/
class TrieNode {
HashMap<Character, TrieNode> children;
private String text; // Maybe omit for space
boolean isWord;
/** Create a new TrieNode */
public TrieNode()
{
children = new HashMap<Character, TrieNode>();
text = "";
isWord = false;
}
/** Create a new TrieNode given a text String to store in it */
public TrieNode(String text)
{
this();
this.text = text;
}
/** Return the TrieNode that is the child when you follow the
* link from the given Character
* #param c The next character in the key
* #return The TrieNode that character links to, or null if that link
* is not in the trie.
*/
public TrieNode getChild(Character c)
{
return children.get(c);
}
/** Inserts this character at this node.
* Returns the newly created node, if c wasn't already
* in the trie. If it was, it does not modify the trie
* and returns null.
* #param c The character that will link to the new node
* #return The newly created TrieNode, or null if the node is already
* in the trie.
*/
public TrieNode insert(Character c)
{
if (children.containsKey(c)) {
return null;
}
TrieNode next = new TrieNode(text + c.toString());
children.put(c, next);
return next;
}
/** Return the text string at this node */
public String getText()
{
return text;
}
/** Set whether or not this node ends a word in the trie. */
public void setEndsWord(boolean b)
{
isWord = b;
}
/** Return whether or not this node ends a word in the trie. */
public boolean endsWord()
{
return isWord;
}
/** Return the set of characters that have links from this node */
public Set<Character> getValidNextCharacters()
{
return children.keySet();
}
}
Even though the algorithm is there I am not able to implement it. Any kind of help would be greatly appreciated.
are you trying to solve this as part of the Coursera's university of San Diego course?
If so then all what you have to do is to follow the algorithm that was written as a comment inside the class.
Any way, I added here a copy of my implementation to this method. Just don't copy and paste it as part of your solution please. Use it as guidance. I added comments in the code to help you understanding my algorithm:
//Trying to find the stem in Trie
String prefixToCheckLowerCase = prefix.toLowerCase();
int completionsCount = 0;
List<String> completions = new LinkedList<String>();
TrieNode traversal = root;
for (int i = 0; i < prefixToCheckLowerCase.length(); i++)
{
if (traversal.getValidNextCharacters().contains(prefixToCheckLowerCase.charAt(i)))
{
traversal = traversal.getChild(prefixToCheckLowerCase.charAt(i));
}
//Means stem not found, returns an empty list
else
return completions;
}
//If current word is an end word, increment the counter and add it to compeltions list
if (traversal.endsWord())
{
completionsCount=1;
completions.add(traversal.getText());
}
List<TrieNode> nodesToBeSearched = new LinkedList<TrieNode>();
List<Character> ChildCharaterList = new LinkedList<Character>(traversal.getValidNextCharacters());
//Filling the list with children of the current node, first level of of the breadth first search
for (int i=0; i<ChildCharaterList.size(); i++)
{
nodesToBeSearched.add(traversal.getChild(ChildCharaterList.get(i)));
}
//while loop for the linked list elements and see if any compeltions exists , inside it we will also check each node children and add them to the list!!!
while (nodesToBeSearched!=null && nodesToBeSearched.size()>0 && completionsCount < numCompletions)
{
TrieNode trieNode = nodesToBeSearched.remove(0);
if (trieNode.endsWord())
{
completionsCount++;
completions.add(trieNode.getText());
}
List<Character> subTrieNodeCholdren = new LinkedList<Character>(trieNode.getValidNextCharacters());
//Adding all next level tries to the linked list , kinda recursive!!!
for (int i=0; i<subTrieNodeCholdren.size();i++)
{
nodesToBeSearched.add(trieNode.getChild(subTrieNodeCholdren.get(i)));
}
}
return completions;
import java.util.ArrayList;
class TrieNode{
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
//ArrayList<String> ans=new ArrayList<>();
public Trie() {
root = new TrieNode('\0');
}
private void add(TrieNode root, String word){
if(word.length() == 0){
root.isTerminating = true;
return;
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
add(child, word.substring(1));
}
public void add(String word){
add(root, word);
}
private void searchHelper(TrieNode root,String word,String ans)
{
try
{
if(word.length()==0)
{
if(root.isTerminating == true)
{
System.out.println(ans);
}
for(int i=0;i<26;i++)
{
TrieNode temp=root.children[i];
if(temp !=null)
{
//ans=ans+temp.data;
//System.out.println("test check "+ans );
searchHelper(temp,word,ans+temp.data);
}
}
}
int childIndex=word.charAt(0)-'a';
TrieNode child=root.children[childIndex];
if(child == null)
{
//System.out.print();
return ;
}
ans=ans+word.charAt(0);
searchHelper(child,word.substring(1),ans);
}
catch(Exception e)
{
//System.out.println("error");
}
}
public void search(String word)
{
String s="";
searchHelper(root,word,s);
}
public void autoComplete(ArrayList<String> input, String word) {
// Complete this function
// Print the output as specified in question
Trie ansTrie = new Trie();
for(int i=0;i<input.size();i++)
{
ansTrie.add(input.get(i));
}
ansTrie.search(word);
}
}
i hope it helps in solving you doubt.
i am already sorry for any indentation errors .
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
public class TrieImpl {
static class Element {
private Trie trie;
private String word;
Element(Trie trie, String word) {
this.trie = trie;
this.word = word;
}
}
static class Trie {
private boolean isLeaf;
private Map<Character, Trie> children;
private Map<Character, Integer> character;
Trie() {
isLeaf = false;
children = new HashMap<>();
character = new HashMap<>();
}
public void insert(String word) {
Trie curr = this;
for (Character ch : word.toCharArray()) {
curr.children.putIfAbsent(ch, new Trie());
int count = (curr.character.get(ch) == null) ? 1 : curr.character.get(ch) + 1;
curr.character.put(ch, count);
curr = curr.children.get(ch);
}
curr.isLeaf = true;
}
public boolean search(String word) {
Trie curr = this;
for (Character ch : word.toCharArray()) {
if (curr.children.get(ch) == null)
return false;
curr = curr.children.get(ch);
}
return curr.isLeaf;
}
public void delete(String word) {
if (search(word)) {
Trie lastSecond = this;
Character charToRemove = word.charAt(0);
Trie curr = this;
int i = -1;
while (i < word.length() && curr != null) {
if (curr.isLeaf && i != word.length() - 1) {
charToRemove = word.charAt(i + 1);
lastSecond = curr;
}
i = i + 1;
if (i < word.length())
curr = curr.children.get(word.charAt(i));
}
lastSecond.children.remove(charToRemove);
}
}
public int findPrefixCount(String word) {
Trie curr = this;
Character lastChar = null;
int count = 0;
for (Character ch : word.toCharArray()) {
if (curr.children.get(ch) == null)
return 0;
if (count < word.length() - 1) {
curr = curr.children.get(ch);
count++;
}
lastChar = ch;
}
if (lastChar != null && curr.character.get(lastChar) != null)
return curr.character.get(lastChar);
else
return 0;
}
public Set<String> autoComplete(String word) {
Trie curr = this;
int count = 0;
String wo = "";
Queue<Element> queue = new LinkedList<>();
Set<String> set = new HashSet<>();
for (Character ch : word.toCharArray()) {
if (count < word.length()) {
curr = curr.children.get(ch);
count++;
wo += ch;
}
}
if (curr != null)
queue.add(new Element(curr, wo));
while (!queue.isEmpty()) {
Element elem = queue.poll();
Trie current = elem.trie;
String temp = elem.word;
if (current != null && current.isLeaf)
set.add(temp);
List<Character> keys = current.character.keySet().stream().collect(Collectors.toList());
for (int i = 0; i < current.children.size(); i++) {
queue.add(new Element(current.children.get(keys.get(i)), temp + keys.get(i)));
}
}
return set;
}
}
public static void main(String[] args) {
Trie head = new Trie();
head.insert("techie");
head.insert("techi");
head.insert("tech");
head.insert("tecabc");
head.insert("tecabk");
head.insert("tecabd");
head.insert("tecalmz");
Set<String> words = head.autoComplete("t");
words.stream().forEach(x -> System.out.println(x));
}
}

Output( ) from a Set class with Singly Linked List Hash Table

I have code that I have been working on going on 10 hours now, and for the life of me, I am unable to get the output( ) of my Set.java to work. Unfortunately I am not allowed to just import the Iterator or HashTable classes from java library. Any ideas or advice would really help.
public class SLL {
public class Node {
private int data;
private Node next;
public Node() {
data = 0;
next = null;
}
public Node(int newData, Node linkValue) {
data = newData;
next = linkValue;
}
public int getData() {
return data;
}
public Node getLink() {
return next;
}
} // End of Node inner class
private Node head;
public SLL() {
head = null;
}
public void addToStart(int itemData) {
head = new Node(itemData, head);
}
public boolean contains(int item) {
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a reference
* to that node. If target is not in the list, null is returned.
*/
public Node find(int target) {
Node position = head;
int itemAtPosition;
while (position != null) {
itemAtPosition = position.data;
if (itemAtPosition == target) {
return position;
}
position = position.next;
}
return null; // target was not found
}
public void outputList() {
Node position = head;
while (position != null) {
System.out.print(position.data + " ");
position = position.next;
}
System.out.println();
}
}
This is the class that I have been working on:
public class Set {
private SLL[] hashArray; // DO NOT MODIFY THIS LINE
private int size = 10; // DO NOT MODIFY THIS LINE
// DO NOT MODIFY THIS METHOD
public Set() {
hashArray = new SLL[size];
}
// DO NOT MODIFY THIS METHOD
private int computeHash(int s) {
return s % size;
}
// COMPLETE BELOW
public void add(int x)
{
int hash = computeHash(x); // Get hash value
SLL list = hashArray[hash];
if(hashArray[hash] == null)
hashArray[hash] = new SLL();
else if(!list.contains(x));
{
// Only add the target if it's not already
// on the list.
hashArray[hash].addToStart(x);
}
}
public void output()
{
SLL tmp = new SLL();
SLL.Node temp = tmp.head;
for(int i = 0; i < size; i++)
{
if(temp == null)
//I think a new instance needs to be created
while(temp.getLink() != null)
{
System.out.println(i + temp.getData() + toString() + " ");
}
}
}
}
And this is the tester it should work with:
public class Tester{
// Have this method to display your name, instead.
static void displayName(){
System.out.println("Program written by Tony.\n");
}
// DO NOT MODIFY THE MAIN METHOD
public static void main(String[] args){
displayName();
Set set1 = new Set();
Set set2 = new Set();
set1.add(3);
set1.add(3);
set1.add(13);
set1.add(23);
set1.add(4);
set1.add(5);
set2.add(15);
set2.add(6);
set2.add(6);
System.out.println("Contents of set 'set1': ");
set1.output();
System.out.println("Contents of set 'set2': ");
set2.output();
System.out.println();
}
}
You need to iterate through the entries in your hash array, and for each non-null entry, iterate through the linked list:
public void output() {
for (int i = 0; i < hashArray.length; i++) {
if (hahArray[i] != null) {
hashArray[i].outputList();
}
}
}
In your for loop as below:
if(temp == null)
//I think a new instance needs to be created
while(temp.getLink() != null)
{
System.out.println(i + temp.getData() + toString() + " ");
}
You should be checking temp != null and you are not moving your node from one to other to traverse over each elements. So you should change it to:
while(temp != null) {
System.out.println(temp.getData() + " ");
temp = temp.getLink();
}
So changing the output( ) a bit to
public void output()
{
SLL tmp = new SLL();
SLL.Node temp = tmp.head;
for (SLL s : hashArray) {
System.out.println(toString() + " " + s);}
}
It still only prints "Programmed by Tony"
and "Contents of set 1:" "Contents of set 2: " without the actual set data?

How to merge single node trees into large tree

I have a project which is to “Start with the tree.java program (Listing 8.1) and modify it to create a binary
tree from a string of letters (like A, B, and so on) entered by the user. Each
letter will be displayed in its own node. Construct the tree so that all the nodes
that contain letters are leaves. Parent nodes can contain some non-letter
symbol like +. Make sure that every parent node has exactly two children.
Don’t worry if the tree is unbalanced.” The book gives us a hint on how to begin. “One way to begin is by making an array of trees. (A group of unconnected trees
is called a forest.) Take each letter typed by the user and put it in a node. Take
each of these nodes and put it in a tree, where it will be the root. Now put all
these one-node trees in the array. Start by making a new tree with + at the root
and two of the one-node trees as its children. Then keep adding one-node trees
from the array to this larger tree. Don’t worry if it’s an unbalanced tree.”
import java.io.*;
import java.util.*;
class Node
{
public String iData; // data item (key)
public Node leftChild; // this node’s left child
public Node rightChild; // this node’s right child
public void displayNode() // display ourself
{
System.out.print('{');
System.out.print(iData);
System.out.print("} ");
}
} // end class Node
class Tree
{
private Node root; // first node of tree
public void setNode(Node newNode)
{root = newNode;}
public Node getNode()
{return root;}
// -------------------------------------------------------------
public Tree() // constructor
{ root = null; } // no nodes in tree yet
// -------------------------------------------------------------
public void traverse(int traverseType)
{
switch(traverseType)
{
case 1: System.out.print("nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("nPostorder traversal: ");
postOrder(root);
break;
}
System.out.println();
}
private void preOrder(Node localRoot)
{
if(localRoot != null)
{
System.out.print(localRoot.iData + " ");
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
// -------------------------------------------------------------
private void inOrder(Node localRoot)
{
if(localRoot != null)
{
inOrder(localRoot.leftChild);
System.out.print(localRoot.iData + " ");
inOrder(localRoot.rightChild);
}
}
// -------------------------------------------------------------
private void postOrder(Node localRoot)
{
if(localRoot != null)
{
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
System.out.print(localRoot.iData + " ");
}
}
// -------------------------------------------------------------
public void displayTree()
{
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while(isRowEmpty==false)
{
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
{
Node temp = (Node)globalStack.pop();
if(temp != null)
{
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
}
else
{
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
"......................................................");
} // end displayTree()
// -------------------------------------------------------------
}
public class Leaves
{
//function used to enter the single node trees into a larger tree
public static void enterLetters(Node localRoot, Tree[] nodeTree, int i)
{
if(localRoot != null && i == nodeTree.length)
{
if(nodeTree.length == i - 1)
{
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
else
{
Node plusNode = new Node();
plusNode.iData = "+";
localRoot.leftChild = plusNode;
localRoot.rightChild = nodeTree[i].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
}
}
public static void main(String[] args)
{
Tree[] forest = new Tree[10];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 10; i++)
{
String letter;
forest[i] = new Tree();
System.out.println("Enter a letter: ");
letter = sc.nextLine();
Node newNode = new Node();
newNode.iData = letter;
forest[i].setNode(newNode);
}
Tree letterTree = new Tree();
Node firstNode = new Node();
firstNode.iData = "+";
letterTree.setNode(firstNode);
enterLetters(letterTree.getNode(), forest, 0);
letterTree.displayTree();
}
}
My problem is trying to get the array of single node trees into the larger tree. I tried making a recursive function but when I display the larger tree it only shows the first node and it is as if the function enterLeaves never did it’s job.
This can't be correct:
public static void enterLetters(Node localRoot, Tree[] nodeTree, int i) {
if (localRoot != null && i == nodeTree.length) {
if (nodeTree.length == i - 1) {
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
} else {
Node plusNode = new Node();
plusNode.iData = "+";
localRoot.leftChild = plusNode;
localRoot.rightChild = nodeTree[i].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
}
}
When you enter this method: localRoot != null, i == 0, and nodeTree.length==10
So the if statement is failing. I am guess the if statement should read:
if (localRoot != null && i < nodeTree.length)
Also, I am pretty sure your second if statement is incorrect also; I believe it should be.
if (nodeTree.length-2 == i) {
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
return;
}
Instead of:
if (nodeTree.length == i - 1) {
localRoot.leftChild = nodeTree[i].getNode();
localRoot.rightChild = nodeTree[i + 1].getNode();
enterLetters(localRoot.leftChild, nodeTree, i + 1);
}
You want to stop when you have two Nodes left to process (nodeTree.length-2 == i) and after you do that you should return instead of entering the remaining letters.
Here's what I came up with that works:
Node.java
/** Represents a node in a binary tree data structure */
public class Node {
private char letter;
private Node leftChild;
private Node rightChild;
public Node(char letter) {
this.letter = letter;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
public Node getRightChild() {
return rightChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getLeftChild() {
return leftChild;
}
/** Returns a String representation of this node. */
#Override
public String toString() {
return "" + letter;
}
}
Tree.java
import java.util.Stack;
/**
* A binary tree
*/
public class Tree {
private Node root;
public void setRoot(Node root) {
this.root = root;
}
public void addToLeft(Node node) {
root.setLeftChild(node);
}
public void addToRight(Node node) {
root.setRightChild(node);
}
public Node getRoot() {
return root;
}
public void displayTree() {
Stack<Node> globalStack = new Stack<>();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while (!isRowEmpty) {
Stack<Node> localStack = new Stack<>();
isRowEmpty = true;
for (int j = 0; j < nBlanks; j++)
System.out.print(' ');
while (!globalStack.isEmpty()) {
Node temp = (Node) globalStack.pop();
if (temp != null) {
System.out.print(temp);
localStack.push(temp.getLeftChild());
localStack.push(temp.getRightChild());
if (temp.getLeftChild() != null ||
temp.getRightChild() != null)
isRowEmpty = false;
} else {
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for (int j = 0; j < nBlanks * 2 - 2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while (!localStack.isEmpty())
globalStack.push(localStack.pop());
} // end while isRowEmpty is false
System.out.println(
"......................................................");
}
}
Forest.java
/**
* A collection of OneNodeTrees combined together in one tree
*/
public class Forest {
private Tree[] forest;
private int forestIndex;
public Forest(int numTrees) {
forest = new Tree[numTrees];
forestIndex = 0;
}
public boolean add(Tree tree) {
if(forestIndex < forest.length) {
forest[forestIndex++] = tree;
return true;
} else {
return false;
}
}
public Tree createMainTree() {
Tree firstTree = new Tree();
firstTree.setRoot(new Node('+'));
firstTree.addToLeft(forest[0].getRoot());
firstTree.addToRight(forest[1].getRoot());
forest[1] = firstTree;
int mainTreeIndex = 0;
Tree tempTree;
for(mainTreeIndex = 2; mainTreeIndex < forest.length; mainTreeIndex++) {
tempTree = new Tree();
tempTree.setRoot(new Node('+'));
tempTree.addToLeft(forest[mainTreeIndex - 1].getRoot());
tempTree.addToRight(forest[mainTreeIndex].getRoot());
forest[mainTreeIndex] = tempTree;
}
return forest[mainTreeIndex - 1];
}
public static void main(String[] args) {
final int numberOfTrees = 6;
Forest forest = new Forest(numberOfTrees);
// Add characters starting from A which has ASCII value 65
int charLimit = 65 + numberOfTrees;
for(int i = 65; i < charLimit; i++) {
// Make new node.
Node newNode = new Node((char) i);
// Add that node to Tree as a root.
Tree newTree = new Tree();
newTree.setRoot(newNode);
// And add that one-node tree to forest(array)
forest.add(newTree);
}
Tree mainTree = forest.createMainTree();
mainTree.displayTree();
}
}
if(localRoot != null && i == nodeTree.length -1)
if you do not subtract one from node tree length you will have a duplicate child under the final parent node with 2 children

Singly linked list Dictionary with intersection method

I have to write a program in which I have to create a singly linked list dictionary in alphabetical order. Then have the words in the dictionary searched in a text file then do a intersect method to see if any word(s) intersect. So far I have created the text file as well as created the two nodes and done the mapping to search for how many times each word appears in this text file. I am completely lost on how to create the singly linked dictionary. I was planning on creating two linked lists(Each with about 5 words in them) and then running an intersection alogirthm method. WOuld that be correct? Or is there an easier way to do it with the code I already have. Here is my code so far:
public class dictionary
{
//variables
dNode head;
int size;
//constructor
public dictionary()
{
head = null;
size = 0;
}
//addFirst method
public void addFirst(dNode s)
{
s.setNext(head);
head = s;
size++;
}
public void addLast(dNode s)
{
if ( head == null )
{
head = s;
}
else
{
s.setNext(null);
dNode w = head;
while ( w.getNext() != null )
{
w = w.getNext();
}
w.setNext(s);
}
size++;
}
//toString Method
public String toString()
{
String w = "";
dNode s = head;
while ( s != null )
{
w += s + "\n";
s = s.getNext();
}
return w;
}
}
public class dNode
{
//variables
String sent;
posting post;
dNode nextNode;
//constructor
public dNode(String sent, posting post, dNode nextNode)
{
this.sent = sent;
this.post = post;
this.nextNode = nextNode;
}
//returns element of this node
public String getSent() {
return sent;
}
//retunrs the next node of this node
public dNode getNext() {
return nextNode;
}
//modifier methods
//sets elements of this node.
public void setSent(String newSent) {
sent = newSent;
}
//sets the next node of this node
public void setNext( dNode newNext) {
nextNode = newNext;
}
//toString method
public String toString()
{
return "Sentence and Posting: \n" + sent + "\n" + post;
}
}
public class pNode {
//variables
int dID;
String word;
int occurence;
pNode next;
//constructor
public pNode(int dID, String word, int occurence, pNode next)
{
this.dID = dID;
this.word = word;
this.occurence = occurence;
this.next = next;
}
//return element of this node
public String getWord() {
return word;
}
//Returns the next node of this node
public pNode getNext() {
return next;
}
//Modifier methods
//set the words of this node
public void setWord(String newWord) {
word = newWord;
}
//sets the next node of this node
public void setNext(pNode newNext){
next = newNext;
}
//toString method
public String toString() {
return "Document ID, Word, Occurence: \n " + dID + ", "
+ word + ", " + occurence;
}
}
public class posting
{
//variables
pNode head;
int size;
//constructor
public posting()
{
head = null;
size = 0;
}
//addFirst method
public void addFirst(pNode s)
{
s.setNext(head);
head = s;
size++;
}
//addLast method
public void addLast(pNode s)
{
if ( head == null )
{
head = s;
}
else
{
s.setNext(null);
pNode w = head;
while ( w.getNext() != null )
{
w = w.getNext();
}
w.setNext(s);
}
size++;
}
//toString method
public String toString()
{
String w = "";
pNode s = head;
while ( s != null)
{
w += s + "\n";
s = s.getNext();
}
return w;
}
}
import java.io.*;
import java.util.*;
public class testFile
{
public static void main (String[] args) throws FileNotFoundException
{
File filename = new File("/export/home/hawkdom2/s0878044/CS503/assignment2/sentences.txt");
Scanner scan = new Scanner(filename);
dictionary Dictionary = new dictionary();
while ( scan.hasNextLine() )
{
String sentence = scan.nextLine();
String[] word = sentence.split(" ");
//first element is document id
int dID = Integer.parseInt( word[0] );
//insertion sort
for ( int i = 2; i < word.length; i++ )
{
for ( int j = i; j > 1; j-- )
{
if ( word[j].compareTo( word[j-1] ) > 0 )
{
String switchs = word[j];
word[j] = word[j-1];
word[j-1] = switchs;
}
}
}
//integer array count
int[] count = new int[word.length];
for ( int i = 1; i < word.length; i++)
{
for ( int j = 1; j < word.length; j++)
{
if (word[i].equalsIgnoreCase( word[j] ) )
{
count[i]++;
}
}
}
posting posts = new posting();
for ( int i = 1; i < word.length; i++ )
{
if ( (i > 1 ) && (word[i].equalsIgnoreCase( word[i-1] ) ) )
continue;
else
{
posts.addFirst(new pNode(dID, word[i], count[i], null) );
}
}
Dictionary.addLast(new dNode(sentence, posts, null) );
}
String[]words ={"cat", "chased", "dogs", "mammals", "roses"};
LinkedList<String> list1 = new LinkedList<String>();
for (String x : words)
list1.add(x);
String[] words2 = {"dislikes", "favorite", "likes", "pink", "red"};
LinkedList<String> list2 = new LinkedList<String>();
for (String y : words2)
list2.add(y);
//print out output
System.out.println(Dictionary);
}
}
And this is my text file containing the sentences:
1 a rose is a rose
2 John chased a cat and the cat chased John
3 cats are mammals but mammals are not cats
4 beavers build dams but i know a beaver that does not
5 my dog chased a cat and the cat attacked my dog
6 my dog likes cats but my cat dislikes dogs
7 my dog likes roses but roses dislike my dog
8 my cat dislikes roses but roses like my cat
9 red roses are not my favorite roses
10 my favorite roses are pink roses

Categories