BinarySearchTree Boat Charter record keeping - java

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. :)

Related

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!

How to remove item from ArrayList, then add back to place of removal?

How do you remove from an ArrayList at a particular index then add back to that same index without the removal causing the ArrayList to compensate for the loss of them item and moving the empty space to the end of the array list?
I've tried:
public void dischargePatient(int bedNumber) {
if (bedNumber < beds.size()) {
beds.remove(bedNumber);
}
}
But this moves the bed at bedNumber to the end of the ArrayList after removing the patient from the bed. How do I keep it at bedNumber?
You want to use a Map object instead. I'm a little rusty at java, but you can define a map of beds like this:
HashMap<Integer,Boolean> occupiedBeds;
and then you can check if an entry is true to see if a bed is occupied, and then set it to false when you discharge a patient. You can initialize the occupiedBeds to a range of false values, or you can just assume an "unset" state means that nobody is in the bed.
You just aspecify the index you want - beds.add(bedNumber, patient);
This pushes the patients that were prior to the addition in locations bedNumber and later to bedNumber+1 ...., thus bringing your list back to the original order.
public void add(int index,
E element)
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
You can use beds.get(bedNumber) and beds.set(bedNumber, patient).
If you want to keep on using an ArrayList, then you can use the method "set(index, null)" instead of invoking the method "remove(index)". This will ensure that the your order does not change.
Example:
0 1 2 3
ArrayList items: [ A, B, C, D ]
items.set(2, null);
0 1 2 3
items: [ A, B, null, D ]
I know this doesn't answer the question asked, but using a list in such a way, expecting the index to reflect the bed number while also expecting the list to define if a bed is taken is a bit broken, or at least highly troublesome. The examples below show how it is easier to manipulate sets and maps and they provide extra information such as total occupied beds without having to code that up yourself.
I suggest you use a Map of Patients rather than a list.
Map<Integer,Patient> patientBeds = new HashMap<Integer,Patient>();
patientBeds.add(bedNumber, patient);
patientBeds.remove(bedNumber);
patientBeds.contains(bedNumber); // is this bed taken?
patientBeds.size(); // total occupied beds, regardless of their numbers
If you don't need the Patient objects, but simply to know which beds are occupied, use a simple Set of Integers
Set<Integer> set = new HashSet<Integer>();
set.add(bedNumber); // help me nurse
set.remove(bedNumber); // I'm going home!
set.contains(bedNumber); // is this bed taken?
set.size(); // total occupied beds, regardless of their numbers
With either of these solutions, your class which holds the Map or Set might have a member which specifies the total number of available beds in the ward. I wouldn't try to build this concept into the Map such as populating the Map with "null" patients.
int totalBeds = 10;
if (bedNumber > totalBeds) {
// send them to the next ward
}

insert into an array from an arraylist

i am doing a hotel room booking system.
i created two array list which is days and rooms.
i created buttons to add value into array list.
example: if monday clicked, then ("monday") inserted into days's array list.
if monday and tuesday clicked, then ("monday") and ("tuesday) inserted into days's array list.
now after all the information is done how do i insert the array list which is days and rooms
into a array, which this array is to function is to store these information as a booking, then use this array to compare with another booking array weather the room being booked or not
As per my understanding of the question you are trying to insert two different ArrayLists into one Array ??
If you are trying to do so.. that is not a good way to do it.. instead create a class having variables as day and room get values in object of that class.. than store it in a array..
hope this helps..
jvaa.util.Map would be a good choice, put the room as the KEY, put a List which contains all reservation date as VALUE.
Reservations:
{
room-1 = [Monday, Tuesday], room-2 = [Sunday], room-3 = []
}
In case you want to check whether a room is booked or not, just retrieve the corresponding List and check size of the List, if the List is empty then the room is not reserved at all.
Exampe for checking reservation of room_1
Map.get(room_1).isEmputy()
For you second comment
Q1: Map.get(room_1).add(DAY-1), for reservation ROOM-1 in DAY-1
Q2:Depends on how do you want to model it. In case you have 3 floors, it is able to index FLOOR/ROOMS in another KEY-VALUE data type , so that you can firstly find all rooms in specific floor by the floor key, then try to add a new room in that floor.
{ FLOOR-1 : [ROOM-1, ROOM-2, ROOM-3, ...], FLOOR-2 : [ROOM-4, ROOM-5, ...]}

Reading back into a BST from file

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.

Beginner Java - inserting node into middle of a linkedlist - what does this do

I'm learning about linked lists right now. I found an example for java that places a new node into the 3rd position on a linked list, but I've only ever seen insertion into a certain spot in the middle of a list like this done using 2 additional nodes, current and previous. I've also never seen anything like .getNext after another one like this. So can someone explain what each part of this snippet of code does and maybe rephrase it using nodes current and previous so I can understand how it relates and compares? Elem is the name given to the node being inserted and you don't have to instantiate current and previous if you do add an explanation involving those. I'll just assume it's already done.
elem.setNext(first.getNext().getNext());
first.getNext().setNext(elem);
numberOfElems++;
Please let me know if you need more info to answer!
elem.setNext(first.getNext().getNext());
As you said, elem is the element being inserted. The line of code above sets elem's next reference to the third element of the list (first.getNext().getNext() references the third element).
first.getNext().setNext(elem);
The second line of code sets the second element's next reference to the new element being inserted. The new element is now inserted in between the old second and third elements, making it the third element in the list.
The last line of code just increments the count of elements.

Categories