So trying to make dijsktra algorithm work and apparently im removing the wrong node according to labb assistant (who is no longer available for help)
These are his comments:
"the loop that you are using in the Dijkstra method (lines 158 - 178). For it to be correct, you need to loop through the outer arcs of your minNode (in your case, "n"), and then pick up the node with the minimum cost as your minNode. In your case, you always remove the first node from the tempNode list instead of the minNode. Please resubmit the modified Network.java file."
and these are lines 157-181:
while (! tempNodes.isEmpty()) { // repeat until all nodes become permanent
Node n = tempNodes.get(0);
double min= Double.POSITIVE_INFINITY;
if(n.value < min){
min = n.value;
}
for(Arc a: n.arcList){
if(n.value + a.weight < a.head.value){
a.head.value = n.value + a.weight; // Update the weight of each node that is adjacent to the minimum-
n.prev = a;
}
tempNodes.remove(n);}//Remove the minimum-weight node n from tempNodes
}
Node k;// Represent a tree by assigning 1 to its arcs and 0 to all other arcs.
for (String nodeName: nodeMap.keySet()) {
k = nodeMap.get(nodeName);
if(k.prev != null) {
k.prev.alvalue = 1.0;
}
}
am i correct in assuming the only issue is that im removing n instead of min mayby?
Il just add the rest of the lines:
public class Network {
// Attributes
public String name;
public HashMap<String, Node> nodeMap;
// Constructor
public Network(String name, String inputFileName) {
// Initialize the attributes
this.name = name;
this.nodeMap = new HashMap<String, Node>();
// You MAY need these local variables to store values or objects
// temporarily while constructing a new Network object
String line, arcID, tailName, headName;
Node tail, head;
double weight;
Arc forwardArc, backwardArc;
try {
// Get access to the contents of an ASCII file
File file = new File(inputFileName);
FileReader fReader = new FileReader(file);
BufferedReader bReader = new BufferedReader(fReader);
// Read the first line, and do nothing to skip it
line = bReader.readLine();
// Read the second line, which represents the first
// (undirected) arc stored in the file
line = bReader.readLine();
// Store each element of the network in forward star.
while (line != null) {
// Split each line into an array of 4 Strings
// using ; as separator.
String[] tokens = line.split(";");
arcID = tokens[0];
tailName = tokens[1];
headName = tokens[2];
weight = Double.parseDouble(tokens[3]);
// Check if nodeMap contains a Node whose name is tailName or headName.
if(nodeMap.containsKey(tailName)){
tail = nodeMap.get(tailName);
}
else{
tail = new Node(tailName, Double.POSITIVE_INFINITY, new LinkedList());
nodeMap.put(tailName, tail);
}
if(nodeMap.containsKey(headName)){
head = nodeMap.get(headName);
}
else{
head = new Node(headName, Double.POSITIVE_INFINITY, new LinkedList());
nodeMap.put(headName, tail);
}
// If not, create it, assign it to tail or head, and add it to nodeMap.
// Otherwise, retrieve it from nodeMap.
// Then, create two Arcs:
// one from tail to head, to be added to outArc of tail
// one from head to tail, to be added to outArc of head.
forwardArc = new Arc(arcID+"a",tail,head,weight);
backwardArc = new Arc(arcID+"b",head,tail,weight);
tail.arcList.add(forwardArc);
head.arcList.add(backwardArc);
// Read the next line
line = bReader.readLine(); }
} catch (Exception e) {
e.printStackTrace();
}
}
// Save
public void save(String outputFileName) {
// This object represents an output file, out.txt, located at ./data/.
File file = new File(outputFileName);
// This object represents ASCII data (to be) stored in the file
FileWriter fWriter;
try {
//writing to the output-file
fWriter = new FileWriter(file);
fWriter.write("TLID "+"\t");
fWriter.write("NAME "+"\t");
fWriter.write("ALVALUE"+"\n");
for (Map.Entry<String, Node> entry : nodeMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Node values = (Node) value;
for (Arc A: values.arcList) {
String TLID = A.name.substring(0,A.name.length()-1);
fWriter.write(TLID+"\t");
fWriter.write(A.name+"\t");
fWriter.write(A.alvalue+"\n");
}
}
fWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void printNodes(){
System.out.println("\tNODE NAME\tWEIGHT");
Node node;
for (String nodeName: nodeMap.keySet()) { // loop thru nodeMap
node = nodeMap.get(nodeName);
System.out.print("\t" + node.name); // \t represents tab space
System.out.print("\t\t" + node.value);
System.out.println();
}
}
public void printArcs(){
System.out.print("TLID "+"\t");
System.out.print("NAME "+"\t");
System.out.print("ALVALUE "+"\n");
for (Map.Entry<String, Node> entry : nodeMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Node values = (Node) value;
for (Arc A: values.arcList) {
String TLID = A.name.substring(0,A.name.length()-1);
System.out.print(TLID+"\t");
System.out.print(A.name+"\t");
System.out.print(A.alvalue+"\n");
}
}
}
public void dijkstra(Node origin) {
// Set the value (representing shortest path distance) of origin to 0
origin.value = 0;
// Create a set of nodes, called tempNodes, whose shortest path distances are not permanently determined. Initially, this set contains all nodes.
List<Node> tempNodes = new ArrayList<Node>();
for (String nodeName: nodeMap.keySet()) {
tempNodes.add(nodeMap.get(nodeName));
}
// Perform Dijkstra
while (! tempNodes.isEmpty()) { // repeat until all nodes become permanent
Node n = tempNodes.get(0);
double min= Double.POSITIVE_INFINITY;
if(n.value < min){
min = n.value;
}
for(Arc a: n.arcList){
if(n.value + a.weight < a.head.value){
a.head.value = n.value + a.weight; // Update the weight of each node that is adjacent to the minimum-
n.prev = a;
}
tempNodes.remove(n);}//Remove the minimum-weight node n from tempNodes
}
Node k;// Represent a tree by assigning 1 to its arcs and 0 to all other arcs.
for (String nodeName: nodeMap.keySet()) {
k = nodeMap.get(nodeName);
if(k.prev != null) {
k.prev.alvalue = 1.0;
}
}
}
private void clearArcWeight() {
Node n;
for (String nodeName: nodeMap.keySet()) {
n = nodeMap.get(nodeName);
for(Arc a: n.arcList){
a.weight = 0.0;
}
}
}
public void dijkstra(Node origin, Node destination) {
dijkstra(origin); // or this.dijkstra(origin);
clearArcWeight();
trace(destination);
}
// Represent a tree by assigning 1 to its arcs and 0 to all other arcs.
private void trace(Node n){
Arc a = n.prev;
while (a != null) {
a.weight = 1.0;
a = a.tail.prev;
}
}
public HashMap<String, Node> getNodeMap(){
return nodeMap;
}
public void dijkstraByName(String string) {
dijkstra(nodeMap.get(string));
}
}
I might be able to give a little hint here... If you look at these lines:
Node n = tempNodes.get(0);
// [...n is not changed here...]
tempNodes.remove(n);
you will realize that the n passed into remove() will never be anything else than the result of 'tempNodes.get(0)'. That's why the first Node is always removed from the list.
Related
I have 6 Red Black trees filled with different data, but the further down I go, the more my trees get mixed up. I've commented out all but two of them, here's my code for those two trees.
Scanner co2DateFile = new Scanner(new File("co2.csv"));
Scanner co2NumFile = new Scanner(new File("co2.csv"));
RedBlackBST co2DateKey = new RedBlackBST();
RedBlackBST co2NumKey = new RedBlackBST();
while (co2DateFile.hasNextLine()) {
String[] line3 = co2DateFile.nextLine().split(",");
if (line3[0].equals("World")) {
LocalDate date = parseDateString(line3[2]);
String stringDate = date.toString();
co2DateKey.root = co2DateKey.put(co2DateKey.root, stringDate, line3[3]);
}
}
while (co2NumFile.hasNextLine()) {
String[] line4 = co2NumFile.nextLine().split(",");
if (line4[0].equals("World")) {
co2NumKey.root = co2NumKey.put(co2NumKey.root, line4[3], line4[2]);
}
}
co2DateKey.inorder(co2DateKey.root);
I'm using the same file for both trees, but using different pieces of data for the keys and values. If I print co2DateKey inorder, then it prints the keys/values for co2DateKey and co2NumKey, but if I comment out the code for co2NumKey, then co2DateKey only prints its own keys/values. I'm not sure where they're getting crossed, so any help would be appreciated.
Here's my RedBlackBST class:
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
import java.io.File;
import java.io.FileNotFoundException;
class Node
{
Node left;
Node right; // initializing Nodes and variables
String key;
String value;
String type;
boolean color; // true means color is red, false is black
Node(String key, String value)
{
this.key = key;
this.value = value;
left = null;
right = null;
color = true; // new nodes are always red
}
}
public class RedBlackBST {
public static Node root = null; // root initialized
public Node rotateLeft(Node myNode)
{
Node child = myNode.right;
Node childLeft = child.left; // assigning variables
child.left = myNode;
myNode.right = childLeft; // rotating nodes to the left
return child;
}
public Node rotateRight(Node myNode)
{
Node child = myNode.left; // assigning variables
Node childRight = child.right;
child.right = myNode; // rotating nodes to the right
myNode.left = childRight;
return child;
}
public void flipColors(Node x, Node y) // flipping colors of two given nodes
{
boolean temp = x.color; // uses temp to store color of first node
x.color = y.color; // first node takes second node's color
y.color = temp; // second node takes first node's color
}
public String get(String key) {
return get(root, key); // this function is called from main, which calls recursive get
}
private String get(Node x, String key) {
while (x != null) {
int cmp = key.compareTo(x.key); // compares current key with the one we are searching for
if (cmp < 0)
x = x.left;
else if (cmp > 0)
x = x.right; // recursively searches through tree until key is found
else
return x.value; // returns value associated with said key
}
return null;
}
public boolean getColor(String key) {
return getColor(root, key); // this function is called from main, which calls recursive getColor
}
private boolean getColor(Node x, String key) {
while (x != null) {
int cmp = key.compareTo(x.key); // same idea as get
if (cmp < 0)
x = x.left;
else if (cmp > 0) // recursively searches through tree to find key
x = x.right;
else
return x.color; // returns color of node associated with said key
}
return false;
}
public boolean isRed(Node myNode)
{
if (myNode == null) // checks color of node passed into function, returns true if red
return false;
return (myNode.color == true);
}
// insertion into Left Leaning Red Black Tree.
public Node put(Node myNode, String key, String value)
{
// inserting node, checks for violations to left leaning red black tree come next
if (myNode == null)
return new Node(key, value);
if (key.compareTo(myNode.key) < 0) // compares keys, recursive calls to find proper spot
myNode.left = put(myNode.left, key, value);
else if (key.compareTo(myNode.key) > 0)
myNode.right = put(myNode.right, key, value);
else if (key.equals(myNode.key) == true) // if key is already in tree, numeric value is replaced
myNode.value = value;
else
return myNode;
// case 1.
// when right child is Red but left child is
// Black or doesn't exist.
if (isRed(myNode.right) && !isRed(myNode.left))
{
myNode = rotateLeft(myNode); // left rotate the node to make it into valid structure.
flipColors(myNode, myNode.left); // swap the colors as the child node should always be red
}
// case 2
// when left child as well as left grand child are Red
if (isRed(myNode.left) && isRed(myNode.left.left))
{
myNode = rotateRight(myNode); // right rotate the current node to make it into a valid structure, then flip colors
flipColors(myNode, myNode.right);
}
// case 3
// when both left and right child are Red in color.
if (isRed(myNode.left) && isRed(myNode.right))
{
myNode.color = !myNode.color; // invert the color of node as well it's left and right child
myNode.left.color = false; // change the color to black
myNode.right.color = false;
}
return myNode;
}
public Iterable<String> keys(Node node, Queue<String> queue) { // uses inorder traversal to put keys in right order
if (node != null)
{
keys(node.left, queue);
queue.add(node.key); // adds each key to queue in correct order
keys(node.right, queue);
}
return queue; // returns queue after all keys have been added
}
public String highest(Node node) {
Node current = node;
while (current.right != null) {
current = current.right;
}
return current.key;
}
void inorder(Node node)
{
if (node != null)
{
inorder(node.left);
System.out.println(node.key + " " + node.value);
inorder(node.right);
}
}
Problem is here:
public static Node root = null; // root initialized
The root is declared static, which means it is shared between all instances of RedBlackBST. They all have the same root. Sure they will be mixed up.
Remove the static keyword.
Below is my bfs algorithm, the algorithm works and finds the node given the start and target. But I want to save edges for the used path in a linkedList to draw the path.
My BFS:
public DGPath breadthFirstSearch(String startId, String targetId) {
V start = this.getVertexById(startId);
V target = this.getVertexById(targetId);
if (start == null || target == null) return null;
DGPath path = new DGPath();
path.start = start;
path.visited.add(start);
// easy target
if (start == target) return path;
// TODO calculate the path from start to target by breadth-first-search
// register all visited vertices while going, for statistical purposes
// if you hit the target: complete the path and bail out !!!
Queue<V> fifoQueue = new LinkedList<>();
Map<V,V> visitedFrom = new HashMap<>();
fifoQueue.offer(start);
visitedFrom.put(start, null);
while (!fifoQueue.isEmpty()) {
V current = fifoQueue.poll();
for (E e : current.getEdges()) {
V neighbour = e.getTo();
path.visited.add(neighbour);
if (neighbour == target) {
while (current != null) {
path.getEdges().addFirst(e);
current = visitedFrom.get(current);
}
return path;
} else if (!visitedFrom.containsKey(neighbour)) {
visitedFrom.put(neighbour,current);
fifoQueue.offer(neighbour);
}
}
}
// no path found, graph was not connected ???
return null;
}
The DGPath is the class that creates the path as shown below:
public class DGPath {
private V start = null;
private LinkedList<E> edges = new LinkedList<>();
private double totalWeight = 0.0;
private Set<V> visited = new HashSet<>();
/**
* representation invariants:
* 1. The edges are connected by vertices, i.e. FOR ALL i: 0 < i < edges.length: edges[i].from == edges[i-1].to
* 2. The path begins at vertex == start
* 3. if edges is empty, the path also ends at vertex == start
* otherwise edges[0].from == start and the path continues along edges[i].to for all 0 <= i < edges.length
**/
#Override
public String toString() {
StringBuilder sb = new StringBuilder(
String.format("Weight=%f Length=%d Visited=%d (",
this.totalWeight, 1 + this.edges.size(), this.visited.size()));
sb.append(start.getId());
for (E e : edges) {
sb.append(", " + e.getTo().getId());
}
sb.append(")");
return sb.toString();
}
public V getStart() {
return start;
}
public LinkedList<E> getEdges() {
return edges;
}
public double getTotalWeight() {
return totalWeight;
}
public Set<V> getVisited() {
return visited;
}
}
I want to save the right edges in de linkedlist edges from the BGPath class (called path in my BFS algo method). So I already saved the used vertices in a map to go back to the root. But when I add the edge to the path it just saves the last edge used multiple times.. The problem is the vertex can have multiple edges, so I need to add the edge from the previous that was pointing to the last "current" until I'm back to the root. But I cant wrap my head around the right way to do this.
The line where I now add the edge to the list of edges is: path.getEdges().add(e)
I think, your problem is the same line, where your are adding the edges, that line is adding the same edge in inner while loop again and again, so you are only traversing back but not adding those nodes to your edges list.
I think, it should be like this
while (!fifoQueue.isEmpty()) {
V current = fifoQueue.poll();
for (E e : current.getEdges()) {
V neighbour = e.getTo();
path.visited.add(neighbour);
if (neighbour == target) {
path.getEdges().addFirst(e):
while (current != null) {
path.getEdges().addFirst(current) ;
current = visitedFrom.get(current);
}
return path;
} else if (!visitedFrom.containsKey(neighbour)) {
visitedFrom.put(neighbour,current);
fifoQueue.offer(neighbour);
}
}
}
// no path found, graph was not connected ???
return null;
}
I have an assignment to create an A* algorithm through a road graph of the UK through a given template (all files for this assignment I have uploaded here
I think, however, that the problem is somewhere in my Planner.java file - the A* algorithm is not finding a node to expand, it just abruptly stops without expanding any nodes at all.
Here is the code for the Planner :
public class Planner implements PlannerInterface<Object> {
// declaration and instantination of our open and closed lists
private final OpenList openList = new OpenList();
private final ArrayList<SearchThroughNodes> closedList;
public boolean empty() {
int lengthOfItem = 0;
return (lengthOfItem == 0);
}
// constructor of closed list
public Planner() {
this.closedList = new ArrayList<>();
}
#Override
public List<GraphEdge> plan(RoadGraph graph, GraphNode origin, GraphNode destination) {
// Temporary costs and other data needed
SearchThroughNodes currentNode, temp1, temp2;
temp2 = new SearchThroughNodes(null, 0, 0, null);
GraphNode temp;
double temporaryCost, heuristics;
ArrayList<GraphEdge> finalResult;
finalResult = new ArrayList<>();
// check if origin and destination exist a.k.a are not set to null
boolean originExistence;
boolean destinationExistence;
destinationExistence = false;
originExistence = false;
if (origin != null && destination != null) {
originExistence = true;
destinationExistence = true;
}
// Pre-requisites for our A-Star to work
if (originExistence == true && !destination.equals(origin) && destinationExistence == true ) {
openList.add(new SearchThroughNodes(origin, 0, Utils.distanceInKM(origin, destination) / 120, null));
} else {
return null;
}
// A-star loop
while (!openList.empty()) {
// Get BEST node to expand
currentNode = (SearchThroughNodes) openList.get();
if (closedList.contains(currentNode)) {
continue;
}
// We reached the destination
// go back through nodes and read path
GraphNode checkCurrNode;
checkCurrNode = currentNode.getGraphNode();
if (destination.equals(checkCurrNode)) {
temp1 = currentNode;
temp2 = (SearchThroughNodes) currentNode.getPrecedingItem();
while (!temp2.getGraphNode().equals(origin)) {
finalResult.add(0, graph.getEdge(temp2.getGraphNode().getId(), temp1.getGraphNode().getId()) );
temp1 = temp2;
temp2 = (SearchThroughNodes) temp2.getPrecedingItem();
}
finalResult.add(0, graph.getEdge(temp2.getGraphNode().getId(), temp1.getGraphNode().getId()));
return finalResult;
}
closedList.add(currentNode);
long currentNodeId = currentNode.getGraphNode().getId();
List<GraphEdge> outEdges = graph.getNodeOutcomingEdges(currentNodeId);
//if expandable
if (outEdges != null) {
// traverse all nodes after currentNode
for (GraphEdge edge : graph.getNodeOutcomingEdges(currentNodeId)) {
long getFromEdge;
getFromEdge = edge.getToNodeId();
//Look at node at the end of the current edge
temp = graph.getNodeByNodeId(getFromEdge);
//store nodeID in tmp2 for traversal of openList
long tmp2GetID;
tmp2GetID = temp.getId();
temp2.setNodeID(tmp2GetID);
// set current edge length in kms,edge max allowed speed and current node cost to variables
// to later compute the temporary cost
double edgeLengthInKMs = edge.getLengthInMetres() / 1000;
double edgeMaxAllowSpeed = edge.getAllowedMaxSpeedInKmph();
double currCost = currentNode.getCost();
//new heuristics and cost
temporaryCost = currCost + edgeLengthInKMs / edgeMaxAllowSpeed;
heuristics = Utils.distanceInKM(temp, destination) / 120;
// Proceed here if node wasn't expanded
if (!closedList.contains(temp2)) {
// if node isn't contained currently in closedList
// if not,check and update accordingly
if (!openList.contains(temp2)) {
openList.add(new SearchThroughNodes(temp,
temporaryCost, heuristics, currentNode));
} else {
temp1 = openList.getNode(temp2);
double tempOneCost = temp1.getCost();
if (tempOneCost > temporaryCost) {
temp1.update(temporaryCost, currentNode);
}
openList.insert(temp1);
}
}
}
}
}
return null;
}
#Override
public AbstractOpenList<Object> getOpenList() {
return openList;
}
}
I have the following code (apologies it's a little long), which works:
public class Node {
public String name;
public List<Node> children = new ArrayList<>();
}
private Node root = new Node();
public static void main(String[] args)
{
TestCreateHierarchy obj = new TestCreateHierarchy();
obj.run();
}
public void run()
{
List<List<String>> objects = new ArrayList<>();
String[] str = {"Person","Manager","Hourly","New"};
objects.add(Arrays.asList(str)) ;
String[] str2 = {"Person","Manager","Salary","Hello"};
objects.add(Arrays.asList(str2)) ;
String[] str3 = {"Person","Manager","Salary", "New"};
objects.add(Arrays.asList(str3)) ;
// String[] str4 = {"Person","Manager","Salary", "New", "John"};
// objects.add(Arrays.asList(str4)) ;
root.name = "ROOT";
for (List<String> seq : objects) {
LOG.debug("------------- NEW SEQUENCE -----------");
LOG.debug(seq);
LOG.debug("--------------------------------------");
insert(seq);
// break;
}
LOG.debug(root.children.size() + " <-- should be 1 ");
}
public Node createNode(List<String> seq, Integer start)
{
if (start >= seq.size())
return null;
Node node = new Node();
node.name = seq.get(start);
node.children.add(createNode(seq, start+1));
return node;
}
public void insert(List<String> seq) {
List<Node> children = root.children;
// Where should we start to build the tree (how
// deep into the sequence?)
int start = 0 ;
// Find the right place to add
for (int i=0; i<seq.size(); i++) {
boolean foundMatchingNode = false;
// if (children.size() == 0)
// continue;
if (children.size() > 0) {
for (Node node : children) {
LOG.debug("HERE --> " + node.name);
if (node.name.equals(seq.get(i))) {
children = node.children;
foundMatchingNode = true;
break;
}
}
}
if (!foundMatchingNode) {
children.add(createNode(seq,i));
break;
}
}
}
My issue is that when I uncomment the str4 part, I get a NullPointerException referring to the insert method, specifically to the for (Node node : children) part.
What do I need to change so that this code works with different hierarchy depths?
The problem is in this function:
public Node createNode(List<String> seq, Integer start)
{
if (start >= seq.size())
return null;
Node node = new Node();
node.name = seq.get(start);
node.children.add(createNode(seq, start+1));
return node;
}
You are adding a child to each newly created node recursively and for the last function call where this condition (start >= seq.size()) satisfies you create a null child.
So, after the insertion of str1, your tree looks like this:
ROOT->Person->Manager->Hourly->New->NULL. Now when you try to enter the str4 your logic for checking matching node name code comes into play. The loop runs fine for entries: Person, Manager, Hourly, New until it runs for the node which is NULL. In the inner for loop for (Node node : children) you have this debugger log: LOG.debug("HERE --> " + node.name);. It is at this point you're getting NullPointerException since your node is null.
Your createNode method is creating adding a null child to the leaf. The NullPointerException occurs because the Node itself is null when you get to the bottom of the tree.
If this is not enough of a hint, please ask for more.
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.