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
Related
I am playing around with circular linked list to represent polynomials with it.
Here is what I have so far:
Class for parts of polynomial:
public class Wielomian {
int wsp;
int a;
int b;
int c;
public Wielomian(){
wsp=0;
a=-1;
b=-1;
c=-1;
}
public Wielomian(int wsp, int a, int b, int c){
this.wsp = wsp;
this.a = a;
this.b = b;
this.c = c;
}
public String toString(){
return wsp+"(x^"+a+")(y^"+b+")(z^"+c+")";
}
}
wsp is coefficient and a,b,c are exponents of x, y and z.
Node:
public class Node {
protected Object data;
protected Node link;
public Node() {
link = null;
data = 0;
}
public Node(Object d,Node n) {
data = d;
link = n;
}
public void setLink(Node n) {
link = n;
}
public void setData(Object d) {
data = d;
}
public Node getLink() {
return link;
}
public Object getData() {
return data;
}
}
List:
class linkedList {
protected Node start ;
protected Node end ;
public int size ;
public linkedList() {
start = null;
end = null;
size = 0;
}
public boolean isEmpty() {
return start == null;
}
public int getSize() {
return size;
}
public void insertAtStart(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Object val , int pos) {
Node nptr = new Node(val,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void deleteAtPos(int pos) {
if (size == 1 && pos == 1) {
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1) {
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size) {
Node s = start;
Node t = start;
while (s != end) {
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++) {
if (i == pos) {
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
}
And I realised I need another add method that will and sort those parts of polynomial while adding - first by exponent of x, if 2 will have equal then by exponent of y and so on.
The elements of list will be parts of polynomial and there also will be "head" which will be linked to the part with highest exponent at "x" and the last part of polynomial will be linked to this "head" making whole list circular. Head will have coefficient that equals 0 and exponats that equal -1 each. But I have no idea how to implement such method without ruining all the links etc. etc. I hope You guys can help me :)
I would also like to know best way to display my polynomial later. Will it be some kind of iteration through parts of polynomial and adding them to String until i reach "head"?
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>();
I have constructed a multi-linked list made up of Friend objects. The Friend class has name and age field. I am trying to insert the Friend objects in ascending order by comparing the names, but I'm running into issues with the part of my code that handles two matching names.
I'm either getting null pointer exceptions or the printed list is out of order.
Populating the list
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Travis", 19);
l.add("Kyler", 14);
l.add("Abby", 10);
l.add("Bob", 19);
l.add("Travis", 12);
l.add("Zander", 99);
l.printList();
}
LinkedList class:
public class LinkedList {
Friend head;
int listcount;
public LinkedList(){
head = null;
listcount = 0;
}
public void add(String name, int age){
Friend node = new Friend(name,age);
if(head==null){
head = node;
return;
}
if(head.name.compareTo(node.name) > 0){
node.nextName = head;
head = node;
return;
}
Friend current = head;
Friend previous = null;
while(current.name.compareTo(node.name) < 0 && current.nextName != null){
previous = current;
current = current.nextName;
}
if(current.name.compareTo(node.name) == 0 && current.age < node.age){
node.nextName = current.nextName;
current.nextName = node;
}
previous.nextName = node;
node.nextName = current;
}
public void printList(){
Friend temp = head;
while(temp!=null){
temp.print();
temp = temp.nextName;
}
}
}
Friend class:
public class Friend {
String name;
int age;
Friend nextName;
Friend nextAge;
public Friend(String name, int age){
this.name = name;
this.age = age;
nextName = null;
nextAge = null;
}
public void print(){
System.out.println(name+" "+age+". ");
}
}
Please change your add() like this(I mean the last lines of your add() method) ;
if (current.name.compareTo(node.name) == 0 && current.age < node.age) {
node.nextName = current.nextName;
current.nextName = node;
} else if (current.name.compareTo(node.name) < 0 ) {
previous.nextName = current;
current.nextName = node;
} else {
previous.nextName = node;
node.nextName = current;
}
Output
Abby 10.
Bob 19.
Kyler 14.
Travis 12.
Travis 19.
Zander 99.
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;
}
}
I want to have a linked list containing an object
Here we have the class.
It is simple and only has a String and one int. Called s and n respectively.
public class test {
String string = new String ();
int n;
public metodo (String string, int n ){
sets(string);
setn(n);
}
public void sets(String string){
this.string = string;
}
public void setn(int n){
this.n = n;
}
public String gets(){
return string;
}
public int getn(){
return n;
}
}
In each node there will be an instance of the class test.
I want to be able to call each node and then call the object in the node calling the class test.
Here is my linked list
import java.io.*;
public class Node
{
BufferedReader br = new BufferedReader( new InputStreamReader ( System.in));
test m;
int n;
static Node next = null;
String string = new String ();
Nodo head = null;
public Nodo (test m, Nodo next) {
this.next = next;
}
public void hoho() throws IOException{
while ( true )
{ // This loop is for making several nodes with diferent information
System.out.println("String");
string n = br.readLine();
System.out.println(" Int ");
n = Integer.parseInt(br.readLine());
m = new test(string, n);
Nodo nod = new Nodo (m, null);
Nodo.siguiente = head;
head = nod;
if ( n == 0 ){ // Manual close of the loop by inserting 0
break;
}
}
}
}
Now I don't really know when to start the object m, if in the start or in the while.