Implementing a .txt file into a 2-3 tree - java

Okey, so I have some problems with my way of thinking again (this time I'm sick). I need to implement a .txt file into a 2-3 tree wich I have made the foundations of.
My Node class
package kth.id2010.lab.lab04;
public class Node {
boolean isLeaf = false;
int numberOfKeys;
String[] keys = new String[2]; //each node can contain up to 2 keys
int[] key1Values = new int[2]; //every key contains 2 values
int[] key2Values = new int[2]; //every key contains 2 values
Node[] subtrees = new Node[3]; //every node can contain pointers to 3 different nodes
Node[] parent = new Node[1]; //every node contains a pointer to a parent node, if root parent is null
Node(Node n) {
n.numberOfKeys = 0;
n.isLeaf = true;
}
}
My Tree class
package kth.id2010.lab.lab04;
public class Tree {
Node root; // root node of the tree
int n; // number of elements in the tree
private Tree(){
root = new Node(root);
n = 0;
root.parent = null;
}
//Return the values of the key if we find it
public int[] get(Node n, String key){
if(n.isLeaf){
if(n.keys[0].equals(key)){
return(n.key1Values);
}
else if(n.keys[1].equals(key)){
return(n.key2Values);
}
else{
return null;
}
}
else if(key.length() < n.keys[0].length()){
return(get(n.subtrees[0],key));
}
else if(n.numberOfKeys == 2 && key.length() < n.keys[1].length()){
return(get(n.subtrees[1],key));
}
else{
return(get(n.subtrees[2],key));
}
}
//put new values to the key
public void put(Node n, int[] value, String key){
if(n.keys[0].equals(key)){
n.key1Values = value;
}
else if(n.keys[1].equals(key)){
n.key2Values = value;
}
else if(n.keys[0].length() < key.length()){
put(n.subtrees[0],value,key);
}
else if(n.numberOfKeys == 2 && n.keys[1].length() < key.length()){
put(n.subtrees[1],value,key);
}
else{
put(n.subtrees[2],value,key);
}
}
public int size(){
return(this.n);
}
}
And my Driver class
package kth.id2010.lab.lab04;
import edu.princeton.cs.introcs.In;
import java.net.URL;
public class Driver {
public static void main(String[] args) {
URL url = Driver.class.getResource("/kap1.txt");
System.out.println(System.getProperty("user.dir"));
In input = new In(url);
String[] usedWords;
while(!input.isEmpty()){
String line = input.readLine().trim();
String[] words = line.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
}
So for my assignment each word in words is 1 key, keyValue1[0]is the occurrence number = index in words and keyValue1[1] is the occurrence count. So my thought was that for each word in wordsI add it to a node and add the index number as the first value, and then I add the word to usedWords and check how many times that word is in words. The only thing i'm stuck with is how to add it as a Node and try to sort it, and put the bigger Node that came befor as it´s parent.

Related

How to create a linked list in java without importing linked lists

i am a CS student in college and i am having trouble with this project where i am supoosed to create a linked list using nodes without importing linked lists, as well as doing a some methods with the list. i am a beginner when it comes to coding, so assume i know nothing, because that is probably the case lol.
import java.io.*;
import java.lang.*;
public class List {
public int listCount = 0;
public char[] linkedList;
public List() throws FileNotFoundException {
}
public List(char[] array) throws FileNotFoundException {
if (array.length == 1) {
Node head = new Node(array[0]);
} else if (array.length > 1) {
Node head = new Node(array[0]);
Node traverse = head;
for (int i = 1; i < array.length; i++) {
while (traverse.nextNode != null) {
traverse = traverse.nextNode;
}
traverse.nextNode = new Node(array[i]);
listCount++;
}
}
}
public List(String w) throws FileNotFoundException {
char[] array2 = new char[w.length()];
for (int i = 0; i < w.length(); i++) {
array2[i] = w.charAt(i);
}
List str = new List(array2);
}
/* Find the character at a index
#param int index
return the character at the chosen index
*/
public char charAt(int index) throws IndexOutOfBoundsException {
char results = linkedList[0];
if (index < linkedList.length && index >= 0) {
results = linkedList[index];
}
return results;
}
public String concat(int index1, int index2) {
return null;
}
/* Determine if the list is empty
return whether the given conditions are true or false
*/
public boolean isEmpty() {
for (int i = 0; i < linkedList.length; i++) {
if (!linkedList.equals(null)) {
System.out.println("This list is not empty");
return false;
}
}
System.out.println("List is empty");
return true;
}
/* Determine the size of the list
return the size of the list
*/
public int size() {
return listCount;
}
/* Create a new String between 2 index's including the start and end index
#param beginIndex is the starting point of the new String
#endIndex is the ending point of new String
return the new String
*/
public String subString(int beginIndex, int endIndex) {
return null;
}
public void insert(Object x) throws IndexOutOfBoundsException {
if (listCount > 100 || listCount < 0) {
throw new IndexOutOfBoundsException("Bag is too large");
} else {
this.linkedList[listCount] = (char) x;
listCount++;
}
}
}
i appreciate any help or pointers ahead of time. we are using a separate node, helper, and driver class as well as a .txt file to assign into my list. i am stuck on the concat and substring methods too, but i want to make sure i am getting the framework correct first. thank you again.
If i understand your question correctly, you are asking how to access a specific type without importing it.
Imports are required to identify which type is referenced when it is used by its simple name. To reference a type without declaring it in the imports you need to use its fully qualified name. For instance
java.util.List<String> someList = new java.util.ArrayList<>();
works without importing List and ArrayList because by declaring the package the class is in it is clear which class is being referenced.
I'll try to do the code later, but here is a book that i found that may help you.
https://cin.ufpe.br/~grm/downloads/Data_Structures_and_Algorithms_in_Java.pdf
I bought a book about DATA STRUCTURE from Pearson company, and it's really a good book, but i don't remember much, it's something like this, that i did in a hurry:
public class List {
private Node head = null;
private Node foot = null;
private Node newNode = null;
private Node auxNode = null;
public List() {
this.head = new Node();
this.foot = new Node();
}
public class Node {
private int adress;
private Node nextNode;
}
public void add(int value) {
this.newNode = new Node();
newNode.adress = value;
if (head == null) {
// Head of the list receive the values of the NEW NODE, so the head of the list
// is not null enymore
head = newNode;
head.nextNode = null;
} else {
// In this case Head is not null
/*The auxiliary node will receive the head and the new Node will become the new Head from the list*/
auxNode = new Node();
auxNode = head;
/*
while(auxNode.nextNode != null ) {
}
auxNode = head;
//head of the list is empty, so we can add the new node
head = newNode;//Here the new node is empty because was transfered to the head
head.nextNode = auxNode; //The head of the list receive the old node that used to be the head
if (head.nextNode == null) {
head.nextNode = newNode;
} else if (head.nextNode != null) {
}*/
}
}
}
```
I hope this help you to get some lead

Hashing using a linkedlist

I'm trying to implement a hashtable using chaining and without any libraries (other than those already in my code), but I'm very stuck. For some reason, the data (100 lines of ints) isn't being added to the list, as seen when it's printed, except for one in the second position (which I assume I need a toString() method for.) Is there any tips or solutions I could get as to how to make this work?
Thanks in advance!
Main + array declaration:
static LinkedList<Node> hashTable[] = new LinkedList[100];
static class Node {
int value;
int key;
}
public static void main(String[] args) throws FileNotFoundException {
File f = new File("Ex5.txt");
Scanner scan = new Scanner(f);
if (f.exists() == false) {
System.out.println("File doesn't exist or could not be found.");
System.exit(0);
}
while (scan.hasNextInt()) {
int n = scan.nextInt();
insert(1, hashFunction(n));
}
for (int i = 0; i < 100; ++i) {
System.out.println(hashTable[i]);
}
}
Insert Function:
public static void insert(int key, int value) {
int index = key % 100;
LinkedList<Node> items = hashTable[index];
if (items == null) {
items = new LinkedList<>();
Node item = new Node();
item.key = key;
item.value = value;
items.add(item);
hashTable[index] = items;
} else {
for (Node item : items) {
if (item.key == key) {
item.value = value;
return;
}
}
Node item = new Node();
item.key = key;
item.value = value;
items.add(item);
}
}
Hashing function:
public static int hashFunction(int value) {
int hashKey = value % 100;
return hashKey;
}
You shall make two changes:
You shall use hashfunction to get the key and keep value as is.
Remove index=key%100 from insert, instead use passed key for
traversing.
Hope this helps.
-------------------------- EDIT --------------------
For printing actual values in linked list, please override toString() method in your Node Class and return a string representation of Key-Value.

I hava a maze search algorithm and is not stopping at end point an is also printing unwanted nodes

I would appreciate any help...
I have 2 maze search algorithms which are DFS and BFS. The starting point is set at 0 and end point is set at 1. The nodes are placed in a stack and starts visiting its neighbors to find the path to 1. The nodes that are not involved in the path to 1 should be erased which is not happening. And also when the path finds the goal which is 1 it is not stopping.
Basically the testMaze path should be 0 5 4 1 whereas BFS is giving me 0 3 5 0 2 11 4 7 1 6 8 9 10 and
DFS is giving me 0, it initiates and it never finds anything. I think the problem might lie in either the printNode function or the visited, isVisited.
Below are the methods related to these problems. Thanks for any help in advance.
import java.util.*;
public class Maze {
public Node startingNode;
public ArrayList<Node> nodes = new ArrayList<>();
public int[][] matrix = new int[100][100];
// to set starting node at 0
public void setStartingNode(Node n) {
this.startingNode = n;
}
public Node getStartingNode() {
return this.startingNode;
}
public void addNode(int n) {
nodes.add(new Node (n));
}
public void visited(int n1) {
for(Node n2 : nodes) {
if(n2.list == n1) {
n2.visited = true;
}
}
}
public boolean isVisited(int n1) {
for(Node n2 : nodes) {
if(n2.list == n1) {
return n2.visited ;
}
}
return false;
}
public Node getNode(int n) {
for(Node n2 : nodes) {
if(n2.list == n) {
return n2;
}
}
return new Node(-1);
}
//TODO get the next unvisited node
public Node getNextNode(Node n) {
int link = n.list;
int i = 0;
while (i<nodes.size()) {
if(matrix[link][i] == 1 && isVisited(i) == false)
{
return (Node)getNode(i);
}
i++;
}
return null;
}
//algorithm uses queue and should find all paths
public void bfs() {
Queue<Node> q=new LinkedList<Node>();
q.add(this.startingNode);
printNode(this.startingNode);
startingNode.visited=true;
while(!q.isEmpty())
{
Node n=(Node)q.remove();//
Node child=null;//
while((child=getNextNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}
// algorithm uses stack and should find fastest solution
public void dfs() {
Stack<Node> s=new Stack<Node>();
s.push(this.startingNode);
startingNode.visited=true;
printNode(startingNode);
while(!s.isEmpty())
{
Node n=(Node)s.peek();
Node child=getNextNode(n);
if(child!=null)
{
child.visited=true;
printNode(child);
s.push(child);
}
else
{
s.pop();
}
}
//Clear visited property of nodes
clearNodes();
}
private void clearNodes() {
int j = 0;
while (j < 0) {
Node n = (Node)nodes.get(j);
n.visited = false;
j++;
}
}
// to print nodes
private void printNode(Node n) {
System.out.print(n.list + " ");
}
}
Below is the main class
import java.util.*;
import java.io.*;
import javax.swing.*;
// C:\Users\Mannie\Desktop\maze1.txt
// C:\Users\Mannie\Desktop\maze2.txt
// C:\Users\Mannie\Desktop\maze3.txt
public class Main {
public static void main(String args[]) throws IOException {
String stringNode;
File file = new File(JOptionPane.showInputDialog("Please enter file path"));
ArrayList<String> nodes = new ArrayList<>();
Maze maze = new Maze();
maze.setStartingNode(new Node(0));
// idea is to convert string into 2D arrays here removing substring " " using .split
try {
try (Scanner sc = new Scanner(new FileInputStream(file))) {
while (sc.hasNextLine()) {
stringNode = sc.nextLine();
nodes.add(stringNode);
String[] segment = stringNode.split(" ");
//for (String val: ){
//the first time this loops the value will be 11, the second time it will be 3
//i have no idea what you
int intNode1 = Integer.parseInt(segment[0]);
int intNode2 = Integer.parseInt(segment[1]);
//System.out.println(intNode);
maze.matrix[intNode1][intNode2] = 1;
maze.matrix[intNode2][intNode1] = 1;
}
// nodes
for (int k=0;k<100;++k)
maze.nodes.add(new Node(k));
}
finally
{
}
} catch (FileNotFoundException e) {
}
Iterator<String> i = nodes.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
// To print bfs results
// also print the system clock time to time the algorithm using
// System.nanoTime();
maze.bfs();
System.nanoTime();
System.out.println();
// To print dfs results
// also print the system clock time to time the algorithm using
// System.nanoTime();
maze.dfs();
System.nanoTime();
}
}
Here is the Node class which just passes through the nodes
public class Node {
public int list;
public boolean visited = false;
public Node(int node) {
this.list = node;
}
}
In your code
public Node getNode(int n) {
for(Node n2 : nodes) {
if(n2.list == n) {
return n2;
}
}
return new Node(-1);
}
you are returning a new Node(-1); instead of null as you expect here:
while((child=getNextNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
This causes wrong nodes to be printed and it will not stop. This code was takes from bfs() but also applies to dfs(). You should return null instead.

Get Words out of a Trie Data Structure

i have the following Trie Data Structure:
public class CDictionary implements IDictionary {
private static final int N = 'z' -'a'+1;
private static class Node {
private boolean end = false;
private Node[] next = new Node[N];
}
private int size = 0;
private Node root = new Node();
#Override
public boolean contains(String word) {
Node node = this.contains(root,word,0);
if (node == null) {
return false;
}
return node.end;
}
private Node contains(Node node, String str, int d) {
if (node == null) return null;
if (d == str.length()) return node;
char c = str.charAt(d);
return contains(node.next[c-'a'], str, d+1);
}
#Override
public void insert(String word) {
this.root = insert(this.root, word, 0);
this.size++;
}
private Node insert(Node node, String str, int d) {
if (node == null) node = new Node();
if (d == str.length()) {
node.end = true;
return node;
}
char c = str.charAt(d);
node.next[c-'a'] = this.insert(node.next[c-'a'], str, d+1);
return node;
}
#Override
public int size() {
return size;
}
The Trie is filled with some words like
for, the, each, home, is, it, egg, red...
Now i need a function to get all Words with a specific length for example the length 3
public List<String> getWords(int lenght) {
}
With the Words mentioned above it should return a list with the words
for,the,egg,red
The Problem is how can i restore these words out of the Trie Structur?
You need to recurse through your structure to a maximum depth of N (in this case 3)
You could do this by adding a couple of methods to your dictionary...
public List<String> findWordsOfLength(int length) {
// Create new empty list for results
List<String> results = new ArrayList<>();
// Start at the root node (level 0)...
findWordsOfLength(root, "", 0, length, results);
// Return the results
return results;
}
public void findWordsOfLength(Node node, String wordSoFar, int depth, int maxDepth, List<String> results) {
// Go through each "child" of this node
for(int k = 0; k < node.next.length; k++) {
Node child = node.next[k];
// If this child exists...
if(child != null) {
// Work out the letter that this child represents
char letter = 'a' + k;
// If we have reached "maxDepth" letters...
if(depth == maxDepth) {
// Add this letter to the end of the word so far and then add the word to the results list
results.add(wordSoFar + letter);
} else {
// Otherwise recurse to the next level
findWordsOfLength(child, wordSoDar + letter, depth + 1, maxDepth, results);
}
}
}
}
(I have not compiled / tested this, but it should give you an idea of what you need to do)
Hope this helps.

Remove element from linked list java

HI :) I have a program about linked lists and we're supposed to be able to delete two numbers if they are the same.. and i know how to do it from the start but how do you delete two numbers if they are in the middle of the linked list?? All 3 run together
Heres my numbers program
import java.util.Scanner;
public class Numbers {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner (System.in);
LinkedList link=new LinkedList();
LinkedList link2= new LinkedList();
System.out.println("Enter in 5 numbers to put in your list");
int num1, num2, num3, num4, num5;
num1 = reader.nextInt();
link.addToStart(num1);
num2 = reader.nextInt();
link.addToStart(num2);
num3 = reader.nextInt();
link.addToStart(num3);
num4 = reader.nextInt();
link.addToStart(num4);
num5 = reader.nextInt();
link.addToStart(num5);
link2.addToStart(num5);
link2.addToStart(num4);
link2.addToStart(num3);
link2.addToStart(num2);
link2.addToStart(num1);
System.out.println("The size of the linked list is " + link.size());
System.out.print("Here is the list ");
link2.outputList();
System.out.println();
System.out.print("Here is the list in reverse order ");
link.outputList( );
System.out.println();
if (num1==num2){
link2.deleteHeadNode(num1);
link2.deleteHeadNode(num2);
System.out.println("Here is the list with the removed numbers");
link2.outputList();
System.out.println();
System.out.println("Here is its size");
System.out.println(link2.size());
}
else if (num2==num3){
link2.deleteHeadNode(num2);
link2.deleteHeadNode(num3);
System.out.println("Here is the list with the removed numbers");
link2.outputList();
System.out.println();
System.out.println("Here is its size");
System.out.println(link2.size());
}
}
}
Here is the node program
public class Node1
{
private Object item;
private int count;
private Node1 link;
public Node1( )
{
link = null;
item = null;
count = 0;
}
public Node1(int num, int newCount, Node1 linkValue)
{
setData(num, newCount);
link = linkValue;
}
public void setData(int num, int newCount)
{
item = num;
count = newCount;
}
public void setLink(Node1 newLink)
{
link = newLink;
}
public Object getItem( )
{
return item;
}
public int getCount( )
{
return count;
}
public Node1 getLink( )
{
return link;
}
}
And here is linked lists program
public class LinkedList
{
private Node1 head;
public LinkedList( )
{
head = null;
}
/**
Adds a node at the start of the list with the specified data.
The added node will be the first node in the list.
*/
public void addToStart(int num)
{
head = new Node1(num, num, head);
}
/**
Removes the head node and returns true if the list contains at least
one node. Returns false if the list is empty.
* #param num1
*/
public boolean deleteHeadNode(int num1 )
{
if (head != null)
{
head = head.getLink( );
return true;
}
else
return false;
}
/**
Returns the number of nodes in the list.
*/
public int size( )
{
int count = 0;
Node1 position = head;
while (position != null)
{
count++;
position = position.getLink( );
}
return count;
}
public boolean contains(String 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.
*/
private Node1 find(String target)
{
Node1 position = head;
Object itemAtPosition;
while (position != null)
{
itemAtPosition = position.getItem( );
if (itemAtPosition.equals(target))
return position;
position = position.getLink( );
}
return null; //target was not found
}
public void outputList( )
{
Node1 position = head;
while (position != null)
{
System.out.print(position.getItem( ) + " ");
position = position.getLink( );
}
}
public boolean isEmpty( )
{
return (head == null);
}
public void clear( )
{
head = null;
}
}
To remove an item in the middle of the linked list, set the previous item's "link" pointer to the "link" pointer of the object you want to remove. For instance, you could add something like this to your LinkedList class:
public void removeNode(Node previousNode, Node nodeToRemove) {
if (previousNode != null) {
previousNode.setLink(nodeToRemove.getLink());
}
}
To think about this better, draw a picture.
N1 -> N2 -> N3 -> N4
N1's "link" is N2, etc. If you want to remove N2, just set N1's "link" to N3.
N1 -> N3 -> N4
One approach it to perform a brute force look up.
For each element you search if is repeated in the list.
If it is, you remove it
and go with the next.
As you may see these three steps may be coded quite easy, the point here is to first understand if they do what you want.
This is the pseudo-code for these three points:
forEach( Element a : inList ) do
// e is the element we want to find repeated.
forEach( Element b : inList ) do
// b is the element in the list.
if( a == b ) then // repeated
inList.remove( a )
break;
endIf
endFor
endFor
This approach will allow you to remove all the repeated elements.
Just remember to remove one item, you have to make sure you don't lose the reference it has. So if you have:
n1 -> n2 -> n3
at some point you have to have n1 and n2 pointing to n3 ( that way n1 keeps the reference n2 has )
n1 -> n3 n2 ->n3
and then remove n2 which leaves you:
n1 -> n3
Now how to code that with your specific data structure is a task you have to perform ;)
Here is a way to do it.
public void delete(int item)
{
while(head.data==item) //For deleting head
{
head=head.link;
}
// For middle elements..................
Node ptr, save;
save=head;
ptr=head.link;
while(ptr!=null)
{
if(ptr.data==item)
{
Node next=ptr.link;
save.link=next;
ptr=next;
}
else
{
save=ptr;
ptr=ptr.link;
}
}
}

Categories