Advanced Data Structures COP5536, Fall 2023
Programming Project Report
RED BLACK TREES & MIN-HEAP
Library Management
Name: Manav Mishra
Under the Guidance of Dr. Sartaj Sahni
- PROJECT OBJECTIVES:
The project, titled "GatorLibrary Management System," aims to create a software system for efficiently managing books, patrons, and borrowing operations in a fictional library, GatorLibrary. The key objectives and requirements are as follows:
-
*Data Structures*: The system should utilize a Red-Black tree to manage books and a Binary Min-heap for managing book reservations. Each node in the Red-Black tree represents a book, containing details like book ID, name, author, availability status, borrower ID, and a reservation heap. The reservation heap is ordered by patron priority, and ties are broken by the timestamp of reservation.
-
*Supported Operations*: The system should support various operations such as:
-
Printing information about specific or a range of books.
-
Inserting, borrowing, and returning books.
-
Deleting books from the library.
-
Finding the closest book by ID.
-
Tracking and analyzing color flips in the Red-Black tree.
-
*Programming Environment*: The project can be implemented in Java, C++, or Python. The program must compile and run on a specified server and should include a makefile to create an executable file named
gatorLibrary. -
*Input and Output*: The program should read input from a text file specified as a command-line argument and write output to a text file named by concatenating the input filename with "_output_file.txt". The program terminates when the 'Quit()' operation is encountered in the input file.
-
*Submission Requirements*: Submissions must include a makefile, well-commented source code, and a PDF report detailing the project, function prototypes, and explanations. All files should be in the first directory after unzipping without nested directories.
-
*Grading Policy*: The grading will focus on the correctness and efficiency of algorithms, with emphasis on correct implementation, comments and readability of the code, and the quality of the report.
-
*Miscellaneous*: It's mandatory to implement Red-Black trees and Binary min-heaps from scratch without using built-in libraries. Collaboration is limited to discussions, and submissions will be checked for plagiarism.
Overall, the project aims to develop a robust library management system utilizing specific data structures and algorithms, with a focus on efficiency, correctness, and good programming practices.
- Technologies Used:
- JAVA
- INTELLIJ IDE
- Steps to Run:
-
Unzip manav_mishra.zip and open the folder.
-
Run Terminal in that directory and run one of the following command:
● javac lib_fetch.java
● java lib_fetch <testfilename>.txt
- Find the output in <testfilename>_output_file.txt generated by the code.
- Function Prototype and Code Structure:
My project is divided into 5 files:
- RBTree.java
- RBTreeNode.java
- BinaryMinHeap.java
- Lib_Fetch.java
- MinHeapNode.java
RBTREE file:
This Java file is an implementation of a Red-Black Tree (RBTree). Here's a brief description of the first few methods based on the code:
- *Constructor
RBTree()*: Initializes a new instance of the Red-Black Tree. In this constructor, the root of the tree is set tonull.
2.*Method insertBook(RBTreeNode newNode)*: This method inserts a new node into the Red-Black Tree. It follows the standard insertion procedure for binary search trees, where the new node is initially inserted like in a regular binary search tree and then the tree is fixed up to maintain the Red-Black Tree properties.
The Red-Black Tree implementation in your Java file includes several methods. Here's a description of each:
-
*
insertBook(RBTreeNode newNode)*: Inserts a new node into the Red-Black Tree. It initially follows the binary search tree insertion logic and then maintains Red-Black Tree properties. -
*
getRoot()*: Returns the root node of the Red-Black Tree. -
*
borrowBook(String bookId)*: This method likely handles the logic for borrowing a book identified bybookId. The specifics of the implementation would define how it interacts with the Red-Black Tree structure. -
*
returnBook(String bookId)*: Manages the process of returning a book with the specifiedbookId. This method probably updates the tree structure or node properties based on the return operation. -
*
printBook(String bookId)*: Prints information about the book with the givenbookId. This could involve finding the node in the tree and displaying its details. -
*
printBooks()*: This method may print details of all books in the Red-Black Tree, possibly through an in-order traversal to display them in a sorted manner. -
*
deleteBook(String bookId)*: Removes the book with the specifiedbookIdfrom the tree. This would include handling the deletion in a way that maintains the Red-Black Tree properties. -
*
findClosestNode(String bookId)*: Finds and returns the node closest to the givenbookId. This could be based on some metric of closeness defined in the tree structure. -
*
deleteNode(RBTreeNode node)*: Deletes a specific node from the Red-Black Tree. Similar todeleteBook, but this one operates directly on a node rather than a book ID. -
*
findBook(String bookId)*: Searches for and returns the node containing the book with the specifiedbookId.
These methods collectively manage the operations of inserting, deleting, finding, and manipulating books within a Red-Black Tree structure, likely representing a library or collection system.
In addition to the public methods in your Red-Black Tree (RBTree) Java implementation, there are several private helper methods that support the main functionalities. Here's a description of each:
-
*
fixInsert(RBTreeNode node)*: A private method used to maintain the Red-Black Tree properties after a new node is inserted. This includes balancing the tree and re-coloring nodes as needed. -
*
rotateLeft(RBTreeNode node)*: Performs a left rotation on the specified node. This is a standard operation in Red-Black Trees used to maintain balance. -
*
rotateRight(RBTreeNode node)*: Executes a right rotation on the given node, which is another key operation for maintaining the balance of a Red-Black Tree. -
*
printBooksInRange(RBTreeNode node, LocalDateTime startDate, LocalDateTime endDate)*: Prints books within a specified date range. This method likely traverses the tree to find and display books that fall within the given date parameters. -
*
findClosestLess(String bookId)*: Finds the closest node with a book ID less than the specifiedbookId. This could be used in various tree operations where relative positioning is important. -
*
findClosestGreater(String bookId)*: Similar tofindClosestLess, but finds the closest node with a book ID greater than the givenbookId. -
*
transplant(RBTreeNode u, RBTreeNode v)*: Replaces one subtree as a child of its parent with another subtree. This is a common operation in tree deletion processes. -
*
minimum(RBTreeNode node)*: Finds the node with the minimum key in the subtree rooted at the given node. This is often used in tree deletion and manipulation operations. -
*
deleteFixup(RBTreeNode x)*: Fixes the Red-Black Tree after a node is deleted to ensure that the tree continues to satisfy all Red-Black Tree properties. -
*
setColor(RBTreeNode node, int color)*: Sets the color of a given node. In Red-Black Trees, nodes are either red or black, and this function is integral to maintaining the tree's properties. -
*
findBookRecursive(RBTreeNode node, String bookId)*: A recursive method to find a book with the givenbookId, starting from the specified node.
These helper methods are essential for the internal workings of the Red-Black Tree, dealing with rotations, balancing, and maintaining the properties that define the Red-Black Tree structure.
- RBTreeNode:
The RBTreeNode.java file contains several methods, each with a specific purpose. Here's an explanation of each method:
-
*
getBookID()*: This method returns the book ID associated with a node in the Red-Black Tree. -
*
getColor()*: This method returns the color (RED or BLACK) of the node, which is a key feature in Red-Black Trees for maintaining balance. -
*
getLeft()*: This method returns the left child of the current node. -
*
getParent()*: This method returns the parent node of the current node. -
*
getRight()*: This method returns the right child of the current node. -
*
setBookID(int bookID)*: This method sets the book ID for the node. -
*
getBookName()*: This method returns the name of the book associated with the node. -
*
setBookName(String bookName)*: This method sets the name of the book for the node. -
*
getAuthorName()*: This method returns the author's name of the book associated with the node. -
*
setAuthorName(String authorName)*: This method sets the author's name for the book in the node. -
*
isAvailable()*: This method returns the availability status of the book (true if available, false otherwise). -
*
setAvailabilityStatus(boolean availabilityStatus)*: This method sets the availability status of the book in the node. -
*
getBorrowedBy()*: This method returns the name of the person who has borrowed the book, if any. -
*
setBorrowedBy(String borrowedBy)*: This method sets the name of the borrower for the book in the node. -
*
getReservationHeap()*: This method returns aBinaryMinHeapobject associated with the node, likely used for managing reservations. -
*
setReservationHeap(BinaryMinHeap reservationHeap)*: This method sets theBinaryMinHeapobject for the node, for managing reservations.
Each method is a standard getter or setter, providing a way to access or modify the properties of a RBTreeNode object, which seems to represent a node in a Red-Black Tree data structure used for storing book-related information.
- BinaryMinHeap:
This Java file defines a class BinaryMinHeap, which is an implementation of a binary min-heap data structure. This structure is commonly used in algorithms and programming for efficiently managing a set of elements ordered by their keys, where the smallest key is always at the top.
Based on the code Here's a brief explanation of each:
-
*Constructor
BinaryMinHeap()*: This initializes theBinaryMinHeapobject, creating anArrayListto store the heap elements. -
*
parent(int i)*: A private helper method to get the index of the parent node of a given node in the heap. -
*
leftChild(int i)*: A private helper method to get the index of the left child of a given node. -
*
rightChild(int i)*: Similar toleftChild, this method gets the index of the right child of a given node. -
*
swap(int i, int j)*: This method swaps two nodes in the heap. It is a common operation in heap maintenance, especially during insertion and deletion. -
*
insert(MinHeapNode node)*: This public method inserts a new node into the heap. It appears to add the node to the end of theArrayListand then adjust its position to maintain the min-heap property. -
*Continuation of
insert(MinHeapNode node)*: This part of theinsertmethod handles the heapify-up process, where the newly added node is swapped with its parent nodes until the min-heap property is satisfied. The method compares the priority of the current node with its parent, and also seems to take into account atimeOfReservationattribute for tie-breaking. -
*
extractMin()*: This public method removes and returns the minimum element from the heap. It handles different cases like when the heap is empty or has only one element. If the heap has more than one element, it swaps the first and last elements, removes the last element (which is the minimum), and then performs heapify-down from the root to restore the min-heap property. -
*
heapify(int i)*: This is a private helper method used in theextractMinmethod. It ensures that the subtree rooted at indexisatisfies the min-heap property. This is done by comparing the node with its children and swapping it with the smaller child if necessary. -
*Continuation of
heapify(int i)*: This method continues with the heapify-down process, ensuring the subtree rooted at the given index maintains the min-heap property by recursively calling itself after a swap if necessary. -
*
peek()*: This method returns the minimum element (the root) of the heap without removing it. It's useful for just checking the top element of the heap. -
*
isEmpty()*: A simple method that checks whether the heap is empty. It returns a boolean value. -
*
size()*: This method returns the number of elements currently in the heap. -
*
decreaseKey(int patronID, int newPriority)*: This method decreases the priority of a specific node identified bypatronIDand adjusts the heap accordingly. This is typically used in algorithms like Dijkstra's shortest path, where the priority of nodes in the heap may need to be updated. -
*
remove(int patronID)*: This method removes a specific node from the heap, identified bypatronID. It performs necessary adjustments to maintain the heap structure after removal. -
*
getAllReservations()*: It appears to return a list of all elements (reservations) in the heap. This might be used for getting a snapshot of all elements in the heap. -
*
contains(int patronID)*: This method checks if a particularpatronIDexists in the heap. It's useful for membership testing.
From the methods outlined, it's evident that this BinaryMinHeap class is tailored for a specific use case, possibly related to managing reservations or similar tasks where priorities can change and fast access to the smallest element is needed. The class provides a comprehensive set of operations for managing a min-heap, including insertion, extraction, updating priorities, and checking for the existence of specific elements.
- MINHEAPNODE:
This Java file defines a class named MinHeapNode. This class is part of a data structure, likely a Min Heap, where each node has certain properties. Here's an overview of the class and its methods:
Class Overview: MinHeapNode
-
*Attributes*:
-
patronID: An integer, possibly identifying a user or an entity. -
priority: An integer where lower values indicate higher priority. -
timeOfReservation: ALocalDateTimeobject, likely representing the time when a reservation or a request was made. -
*Constructor*:
-
The class has a constructor that initializes the
patronID,priority, andtimeOfReservationattributes. -
*Methods*:
-
There are getters and possibly setters (not fully visible in the preview) for each attribute. These methods are standard in Java for accessing and modifying private class attributes.
this class is designed to represent an element in a Min Heap structure, where each element has a priority and is associated with a timestamp (timeOfReservation). The Min Heap is a popular data structure used in various applications, including priority scheduling, queue management, and efficient sorting algorithms.
- Lib_fetch:
The file lib_fetch.java you've provided appears to be a Java class that includes various methods and attributes. From the initial preview of the file, here is an overview:
Class Overview: lib_fetch
-
*Attributes*:
-
inputFileName: A static variable likely used to store the name of an input file. -
myLib: An instance ofRBTree(presumably a Red-Black Tree), used to storeBookobjects. This indicates that the class is related to library management or book tracking.
The lib_fetch.java file is a comprehensive Java class designed for a library management system. Here's a detailed report on the class and its methods:
Class Overview: lib_fetch
-
*Purpose*: The class seems to manage a library system, handling operations like adding, removing, and querying books, as well as handling reservations. It uses a Red-Black Tree for efficient data management.
-
*Key Attributes*:
-
inputFileName: Static variable for storing the input file name. -
myLib: A private instance ofRBTree, indicating usage of a Red-Black Tree data structure.
Key Methods:
- *fetchInputParameter*
-
*Purpose*: Extracts a specific parameter from a comma-separated string based on its index.
-
*Parameters*:
String parameters,int index. -
*Return*: Extracted parameter as a String.
- *performOperation*
-
*Purpose*: Reads operations from an input file and performs them. The operations include adding, removing, and querying books, among others.
-
*Parameters*:
String inputFileName. -
*Exception*:
IOException.
- *PrintBook*
-
Part of the
switchstatement inperformOperation, it appears to handle printing book details. -
*Parameter Extraction*: Uses
fetchInputParameterto extract book ID from parameters.
- *AddBook*
- Handles adding a new book to the system.
- *RemoveBook*
- Manages the removal of a book from the system.
- *CheckOutBook*
- Deals with the process of checking out a book.
- *ReturnBook*
- Manages the return of a borrowed book.
- *FindClosestBook*
-
*Purpose*: Finds the two books closest to a given target ID and returns details.
-
*Parameters*:
Integer targetID. -
*Logic*: Determines closeness based on the absolute difference in IDs and handles edge cases accordingly.
- *printBookOutput*
- A helper method to format and return the details of a book.
- *Main Method*
- Processes command-line input and initiates operations.
Analysis:
-
The class is designed to interact with an external file, likely containing a list of commands or operations to perform on the library system.
-
Use of a Red-Black Tree suggests a focus on efficient data handling, especially for operations that require sorting or rapid access, like finding a book.
-
Exception handling and input validation are integral parts of the system, ensuring robust operation.
-
The class is modular, with distinct methods handling specific operations, enhancing readability and maintainability.
Conclusion:
lib_fetch is a well-structured Java class designed for efficient library management, demonstrating good programming practices such as modularity, encapsulation, and efficient data structures. This class can be a part of a larger library management system or serve as a standalone tool for managing a collection of books.
DEFENCE for colourflipcount
According to the logic of my code I have flipped the color wherever the flip takes place.
