Reading back into a BST from file - java

This is kind of a confusing question so I apologize as I'm not quite sure how to phrase it. Basically what I'm doing is working with sorting binary search trees. Throughout the program, the user adds a record to the tree, which is a node containing (int studentNumber, String firstName, String lastName, String major, double gpa). At the end of the program, the nodes are transposed to a LinkedList with a custom Node class I made, and then that list is serialized into a file.
Now, on start up, I want to basically read that file back into another list, display the list, then add it back into the BST so it can be sorted in various ways. My question stands on the point of reading each line (node) in the file and pulling the fields (int studentNumber, String firstName, String lastName, String major, double gpa) back into the tree from each "node". This is what I have so far in my read section:
public void loadRecord(LinkedList list) {
File file = new File("records.txt");
try
{
LinkedList<Node> list2;
ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
list2 = (LinkedList<Node>)input.readObject();
if (list2.size() > 0){
list.addAll(list2);
}//end if
else {
System.out.println("No elements");
}
}
//Catch Exceptions
//display list
}//end loadRecord
Once again.. I apologize if this makes no sense at all. And it's very possible I'm going in the completely wrong direction, so I appreciate any feedback. Please let me know what you think!

First, a
linked list and a binary search tree are two different data structures. You can't make one with another.
Let's say you have a list of numbers you want to store. The data is added to both structures in the same order. The linked list will look something like:
|5|-->|3|-->|7|-->|2|-->|6|-->|4|-->|8|-->|1|
"|x|" represents a node with x the data stored in it.
The arrow represents the reference a node has to its next.
data is ordered the same way it is entered.
The binary search tree:
5
/ \
/ \
3 7
/ \ / \
2 4 6 8
/
1
For each parent node there is a reference for a left node and a right node. The data in the left child node is smaller than the data in parent node and the data on the right child node is larger on that of the parent.
Therefore, whatever data is being entered it must be 'comparable' in a sense that one value can be larger or smaller than another. So if your data stored is students then one student must be of larger value than another(higher gpa, larger student number, last alphabetically in name, etc.).
Unlike a linked list, the standard API doesn't provide a binary search tree class.So you have implement your own. You need to be familiar with recursion to implement the BST. Make sure you decide how students are compared and implement the tree accordingly. Here is a link that can help :Binary Search Tree and Tree Traversal .
Next, you need to extract the student info from the record file and store it in the tree. It would help if you stated how the student information is ordered in the record.txt file.For now, I will assume that it is ordered such that data of each student is written in one line. I would implement a method in custom node(should called student) class that takes in a line,parses it, and store the data in the student's fields.
Then I would make a while loop that creates a new student, adds the current line to the appropriate method of the student object, and adds the student object into the tree as long as there is a next line in the input stream.
As I said, I will need more information on record file to explain further. Let me know if you need anymore clarifications.

Related

Convert General "Family" Tree to Binary Tree (Not BST)

I am currently considering different ways to accomplish the task of converting a family-type general tree (where each parent can have as many children as necessary) to a binary tree such that the left child of the parent node is inserted to the left of the parent and the right child of the parent node is inserted to the right of the (oldest) child node and so on.
This is the structure of how the binary tree must look like when converted from the general tree: https://www.geeksforgeeks.org/convert-a-generic-treen-array-tree-to-binary-tree/
I fed in my data by creating class object GTNode for the General Tree to add the nodes with the following values being passed:
//name = value1; numChildren = value2
GTNode gtn = new GTNode (String name, int numChildren);
No issues with constructor, this is purely to illustrated the main focus of the node is indeed the name of the family member. Thus this really can't be converted and sorted by a Binary Search Tree and is not the point of the resulting program I'm trying to create.
I was able to create methods to traverse the tree just fine, but it really doesn't help in the conversion process to the CONVERTED binary tree.
Therefore I created an additional section of code to create a linked list of the data. The reason why I did this was to establish pointers along the list which would point to the correct parent to add children to. Siblings would then be added to the right of the oldest sibling based on pointers based on where we were along real-time adding of nodes in the tree. By this time you can imagine I have two pointers going in my linked list traversal and three pointers along the tree nodes.
I can't seem to make good progress on an algorithm to create this binary tree from the data. here's a little sample code mostly pseudo code to show you basically how I'm adding nodes to the converted-style binary tree based on general tree data.
p=q=first; //initialize to first node f the linked list of family data
//ex. [Tom, 2] [Marc,1] [Ron,0] [Billy, 0] where Marc and Ron are Tom's children, and Billy is Marc's child)
z=root;
//I already established x, y = root earlier and moved pointer .next in order to add children nodes to the siblings
//here we establish x and y pointers for the tree and add our root node and first child node, which will always be to the left.
//I left it out of the while loop, because I was running into problems with null pointers.
{
while (p.next!=null && q.next!=null)
{
for (i = n; i>0; i--) //int n = node.numChildren; was declared earlier and then decreased
// n-=1 to accommodate the first child being added to left of parent node;
{
//add nodes left or right to parent node: still trying to figure out the appropriate condition
//statements to determine addLeft or addRight from node
}
//here we change the pointer of the GENERAL tree parent node based on the linked list
// add new to binary tree to the right of the last child i.e.
y = new BTNode(p.value,p.numChildren);
y = x.right;
x = y.parent;
x = y; //move pointer along
q = q.next; //q moves from Tom to Marc.
n = q.numChildren;
//go to beginning of while loop and as you can see, if n>0 it iterates based on the number of children
// if n=0 exits loop and creates a new node to the right
}
}
I'm wondering if this is an acceptable track to go down in terms of operability. Optimization I'm not as focused on because this is a difficult task... but could be taken into account.
Looking for pseudocode or java code shippers that would help in establishing an algorithm along these lines, or error in my logic. Again, not looking for an argument against doing a conversion like this because I want to see what it would look like as is.
Thanks!

How to remove nodes with java API for graphstream?

I currently use the Graphstream API for Java for my project.
I wan't to delete or add Nodes on command.
With JFrame & co. I initialized a console so I can just insert
"addNode()" or "removeNode(id)" in order to get the result.
A Interface shows the nodes with a number next to them(the ID).
When I delete one node, I want all nodes with higher ID to change their ID,
but I did not figure out a way jet to change the ID of one node.
F.e. I have:
graph.addNode(0);
graph.addNode(1);
graph.addNode(2);
When deleting a Node:
graph.removeNode(0);
I want 1,2 to be changed to 0,1 without reinitializing the complete graph.
Is there a way to achieve this behaviour? I thought about something like:
graph.getNode(1).setID(0);
Unfortunately I have only access to .getID() and can't manipulate it this way.
Thanks
Nodes ids are strings and they are immutable (no renaming, no setId()).
Now what you are doing in your example is different. You are using the index-based access to the nodes. Indices are integers and correspond to arbitrary nodes in the graph, they are not associated to the ids.
When you do graph.addNode(0), the integer is converted to the string "0". Then when you do graph.removeNode(0), you are removing a node that was indexed as the first of the list of nodes. But it does have to be the node this id "0".
You can remove nodes with index (integer) 0 as long as there are nodes in the graph (graph.removeNode(0)) but you can only remove the one node with id "0" once (graph.removeNode("0")).

Sorting nodes under two conditions?

only just started learning java and was stuck on this problem.
Let's say I have a list of employees (I'll use only three of this examples) in no particular order and I go through the list and create a sorted link of nodes that all contain a name and salary per week. These three nodes would individually look like so:
(John, 1000)
(Bob, 1000)
(Adam, 1000)
And I wanted to sort it first by salary then alphabetically by name so all the nodes connected would look something like this:
(Adam, 1000)(Bob, 1000)(John, 1000)
I also have a way of increase the salary so if I were to do something like bobNode.increaseBy(200) (the amount increased at a time will always be the same i.e 200 every time the method is called for every name) the connected nodes would update and look something like this
(Bob, 1200)(Adam, 1000)(John, 1000)
Is there any efficient or easy way to do this? Currently, I have a compareTo method in my Node class that returns this.name.compareTo(other.name) so the nodes are sorted alphabetically as I go through the list of employees. Is there anyway to check for both conditions and sort?
I was thinking about doing something like if salary.compareTo(other.salary) == 0 compare the names instead, but since the nodes would already exists in the linked list it wouldn't really work.
What about adding and sorting the nodes alphabetically first and whenever salary of a node is adjusted removing that node and adding it again to the correct position?
Another idea I had that's similar to the previous was to remove the adjusted nodes and creating a new linked list of nodes that contains all the nodes with that amount of salary sorted alphabetically. I will then add these new nodes after I have gone through the list of employees. Wouldn't this be a bit problematic if say I had a list of 200,000 employees with a wide range of salary thus I would have to create and iterate through many nodes?
I also wanted to note that the salary can increase without having all the employees be added first.
Any help and ideas would be greatly appreciated!

Java filing and highscore

Hi so I have an assignment due in 6 hours and I am completely lost. I have new methods added to my existing work done so far but I don't know how to do them.
The text file has names and scores, and the first method needs to check if the score is among the top 10 and return true/false:
the last method that I am lost in needs to write the high score into highscore.txt file, at the correct position(in descending order), the method uses readHighScore() method to find the line number where the record should be inserted.
public static void recordHighScore(String name, int score){
}
You can't insert data into text files. You can only append/rewrite. These are the steps:
Read data and store into objects.
Get the highest/lowest from the objects (you can also sort them with Collections.sort() or Arrays.sort())
Write the sorted objects back into the text file. (You will be overwriting the text file with new data)

BinarySearchTree Boat Charter record keeping

This is for a Homework assignment
For this assignment that I have to do, I have to create a recordkeeping log for a cruise liner for a month (represented by the numbers 1-31). There is 1 cruise a day that can hold up to 6 people. If the number of people trying to book on a certain day passes 6, then they will be added to a queue. The current passenger list is supposed to be held in a BinarySearchTree. Basically we are to read from a provided file information about a person object and insert them into a tree corresponding to the day they picked. (The file will give information in this order: (transactionCode day lastName firstName)) Where transaction code represents action taken (Add Passenger , Delete (Deletes passenger from tree and adds next passenger from queue), Print (Prints current BST and waiting list of day), Departure (Prints final list and queue of day).
The Question I am asking, is in regards to a method of creating a BST and a Queue that represents each and every day in a single method and adding to those BSTs. I am going blank in a method to accomplish this. I have already created a person object class, a BST Class, and a queue class. I can create an Add method in my passenger class, but how would I check to see if a tree already exists for a specific day, and add to that tree instead of creating a new one?
I am at a loss, if you need to see any classes, leave a comment. Thank you in advance.
If I understand what you're saying, here's what I think you should do.
Have a array of nodes, each one representing a day.
Make the nodes hold the letter x so has to shoe that they are empty.
Have the root nodes pointing left and right until there are six nodes in each tree.
The also make another array, again, each one representing a day.
Fill each node with a x to show that it is not occupied.
Now when you want to book a passenger, go to the day by going to it's index in the array of binary trees
If the there's a x in it, that mean it's free, so store the passenger's name
If there's another in it, check the left and right nodes until all six are checked
If all six are filled then go to the Queue array of node, go to the index of the day, if it's a x, replace it with the passenger's name
If it's not an x AND the root pointer is not NULL, say root->next = new Node (passenger's name);
If the root pointer is a NULL, you'll have to go to the last person in the queue and then add on the new person.
If a passenger is deleted for a day, go to the index in the queue, add the root node to the binary tree
Then remove the name in the root node, swap it with the next in line...until there's no more in line.
I hope this helps. :)

Categories