diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a6e97c7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..cb2d165 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "daily" \ No newline at end of file diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml new file mode 100644 index 0000000..3dc14b4 --- /dev/null +++ b/.github/workflows/linter.yml @@ -0,0 +1,34 @@ +name: Lint Code Base + +on: + push: + branches: main + pull_request: + branches: main + +jobs: + build: + name: Lint Code Base + + runs-on: ubuntu-latest + + permissions: + contents: read + packages: read + statuses: write + + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Lint Code Base + uses: github/super-linter/slim@v5 + env: + VALIDATE_JSCPD: false + VALIDATE_KOTLIN_ANDROID: false + VALIDATE_ALL_CODEBASE: false + DEFAULT_BRANCH: "main" + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..5edc278 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,39 @@ +name: test with coverage +on: + push: + pull_request: +jobs: + build: + name: Build and Run Tests + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ ubuntu-latest, windows-latest, macos-latest ] + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-java@v3 + with: + distribution: temurin + java-version: 11 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Build with Gradle + run: ./gradlew build + + - name: JaCoCo Coverage Report + if: runner.os != 'Windows' + env: + report_path: trees/build/jacoco/report.csv + run: | + awk -F"," '{ instructions += $4 + $5; covered += $5; branches += $6 + $7; branches_covered +=$7 } END { print "Instructions covered:", covered"/"instructions, "--", 100*covered/instructions"%"; print "Branches covered:", branches_covered"/"branches, "--", 100*branches_covered/branches"%" }' "$report_path" + + - uses: actions/upload-artifact@v3 + if: ${{ github.ref == 'refs/heads/main' }} + with: + name: test-and-coverage-reports + path: trees/build/reports + retention-days: 365 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..395679d --- /dev/null +++ b/.gitignore @@ -0,0 +1,184 @@ +# Created by https://www.toptal.com/developers/gitignore/api/kotlin,java,gradle,intellij +# Edit at https://www.toptal.com/developers/gitignore?templates=kotlin,java,gradle,intellij + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### Kotlin ### +# Compiled class file + +# Log file + +# BlueJ files + +# Mobile Tools for Java (J2ME) + +# Package Files # + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof +### mac gabage files +.DS_Store +# End of https://www.toptal.com/developers/gitignore/api/kotlin,java,gradle,intellij diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..6d981b3 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# Binary search trees library +> An open source library written in Kotlin to work with data structures such as AVL tree, red-black tree, and binary search tree. +## 🖍 Used technology +![Kotlin](https://img.shields.io/badge/-Kotlin-61DAFB?logo=kotlin) +![Junit](https://img.shields.io/badge/Tests-Junit-green) +![Neo4j](https://img.shields.io/badge/Neo4j-008CC1?style=for-the-badge&logo=neo4j&logoColor=white) +![Postgresql](https://img.shields.io/badge/PostgreSQL-316192?style=for-the-badge&logo=postgresql&logoColor=white) +![Docker](https://img.shields.io/badge/Docker-316192?style=for-the-badge&logo=Docker&logoColor=white) +## :package: Getting started +To build the library run + +```sh +./gradlew build +``` +To run PostgreSQL with docker: +```sh +./start-db.sh +``` +or +```sh +./start-db.bat +``` + +## Using binary search trees +Any data (provided with `Comparable` key) can be stored in trees. +For example: + +```kotlin + import bst.BSTree + val tree = BSTree(1, "apple") + tree.insert(7, "orange") + tree.insert(28, "Alice") + tree.insert(4, "Bob") +``` +Constructor takes two arguments: `key` and `value`, thus instantiating a root node (you can delete it, +but you cannot create an empty tree). +`insert` method also takes same arguments and adds a node with specified `key` and `value` properties to the tree. +Method `setName` allows you to set the name of a tree. + +Find or remove element from tree: +```kotlin + tree.find(4) // returns "Bob" + tree.remove(1) +``` +`find` and `remove` methods take some `Comparable` key as an argument. + +AVL and red-black trees implement the same methods. + +## Storing binary search trees +AVL tree can be saved to and loaded from JSON file. +For example: +```kotlin + val tree = AVLTree(1, "apple") + tree.setName("test") + val controller = JsonController() + controller.saveTreeToJson(test) + println(controller.readFromJson("test")?.treeName) +``` +You can also save binary search tree to SQL database: +```kotlin + val tree = BSTree(1, "apple") + tree.setName("test") + val controller = SQLController() + controller.saveTreeToDB(test_data) + val remTree = controller.getTree("test") +``` +And you can save red-black tree to Neo4j database +```kotlin + val tree = RedBlackTree(1, "apple") + tree.setName("test") + val controller = Neoj4Conroller() + contoller.saveTree(tree) + val remTree = controller.loadTree("test") +``` + +An example of interacting with trees through a graphical interface +![Example gif](https://github.com/spbu-coding-2022/trees-3/blob/add-ui/readme_gif/example1.gif) \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..b24ba3a --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + id("org.jetbrains.kotlin.jvm") version "1.8.10" + id("org.openjfx.javafxplugin") version "0.0.12" + application +} + +javafx { + version = "18" + modules("javafx.controls", "javafx.fxml") +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + implementation("no.tornado:tornadofx:1.7.20") + implementation(project(":trees")) +} + +application { + // Define the main class for the application. + mainClass.set("app.AppKt") +} diff --git a/app/src/main/kotlin/app/App.kt b/app/src/main/kotlin/app/App.kt new file mode 100644 index 0000000..8a2e6bf --- /dev/null +++ b/app/src/main/kotlin/app/App.kt @@ -0,0 +1,19 @@ +package app + +import app.view.MainView +import tornadofx.App +import tornadofx.launch + +/** + * Represents the main application class. + */ + +class MyApp : App(MainView::class) + +/** + * The main entry point of the application. + */ + +fun main() { + launch() +} diff --git a/app/src/main/kotlin/app/controller/AVLController.kt b/app/src/main/kotlin/app/controller/AVLController.kt new file mode 100644 index 0000000..03f2a8e --- /dev/null +++ b/app/src/main/kotlin/app/controller/AVLController.kt @@ -0,0 +1,196 @@ +package app.controller + +import bst.AVLTree +import bst.db.controllers.JsonController +import bst.nodes.AVLNode +import javafx.collections.FXCollections +import javafx.collections.ObservableList +import javafx.scene.control.Tooltip +import javafx.scene.layout.Pane +import javafx.scene.layout.StackPane +import javafx.scene.paint.Color +import javafx.scene.shape.Circle +import javafx.scene.shape.Line +import javafx.scene.text.Text +import javafx.scene.text.TextBoundsType +import tornadofx.Controller +import kotlin.math.min + +/** + * The AVLController class is responsible for managing AVL trees. + * + * It extends the Controller class and provides additional functionality for working with AVL trees. + */ + +class AVLController : Controller() { + + /** + * Returns a Boolean value indicating whether the given String can be converted to an Integer. + * + * @param s the String to be checked + * @return true if the String can be converted to an Integer, false otherwise + */ + + fun isNumeric(s: String): Boolean { + return try { + s.toInt() + true + } catch (e: NumberFormatException) { + false + } + } + + /** + * Inserts a new node with the given key and value into the AVL Tree and redraws the tree in the tree pane. + * + * @param tree the AVL Tree to insert the node into + * @param treePane the Pane where the AVL Tree is displayed + * @param key the key of the new node to be inserted + * @param value the value of the new node to be inserted + */ + + fun insertNode(tree: AVLTree, treePane: Pane, key: Int, value: String) { + tree.insert(key, value) + drawTree(tree, treePane) + } + + /** + * Clears all nodes from the AVL Tree and removes all nodes from the tree pane. + * + * @param tree the AVL Tree to be cleared + * @param treePane the Pane where the AVL Tree is displayed + */ + + fun clearTree(tree: AVLTree, treePane: Pane) { + tree.clear() + treePane.children.clear() + } + + /** + * Draws the AVL Tree in the tree pane. + * + * @param tree the AVL Tree to be drawn + * @param treePane the Pane where the AVL Tree is displayed + */ + + fun drawTree(tree: AVLTree, treePane: Pane) { + treePane.children.clear() + val root = tree.getRoot() + if (root != null) { + drawNode(root, treePane, treePane.width / 2.0, treePane.width / 2.0, 250.0) + } + } + + /** + * Draws the given [AVLNode] in the [treePane] at the specified [x] and [y] coordinates with the given [offsetX]. + * @param node the [AVLNode] to be drawn + * @param treePane the [Pane] in which the [AVLNode] is to be drawn + * @param x the x-coordinate of the [AVLNode] in the [treePane] + * @param y the y-coordinate of the [AVLNode] in the [treePane] + * @param offsetX the horizontal offset from the [x] coordinate at which the [AVLNode] should be drawn + */ + + private fun drawNode(node: AVLNode, treePane: Pane, x: Double, y: Double, offsetX: Double) { + val circleRadius = 20.0 + val circle = Circle(circleRadius) + circle.fill = Color.WHITE + circle.stroke = Color.BLACK + + val nodeText = Text(node.key.toString()) + nodeText.boundsType = TextBoundsType.VISUAL + + val scale = + min(circleRadius * 1.3 / nodeText.boundsInLocal.width, circleRadius * 1.3 / nodeText.boundsInLocal.height) + nodeText.scaleX = scale + nodeText.scaleY = scale + + val nodeStackPane = StackPane(circle, nodeText) + nodeStackPane.relocate(x - circleRadius, y - circleRadius) + + val tooltip = Tooltip("value: ${node.value}") + Tooltip.install(nodeStackPane, tooltip) + + treePane.children.add(nodeStackPane) + + if (node.left != null) { + val leftX = x - offsetX + val leftY = y + 50 + val leftLine = Line(x, y + circleRadius, leftX, leftY - circleRadius) + treePane.children.add(leftLine) + drawNode(node.left!!, treePane, leftX, leftY, offsetX / 2.0) + } + + if (node.right != null) { + val rightX = x + offsetX + val rightY = y + 50 + val rightLine = Line(x, y + circleRadius, rightX, rightY - circleRadius) + treePane.children.add(rightLine) + drawNode(node.right!!, treePane, rightX, rightY, offsetX / 2.0) + } + } + + /** + * Retrieves a list of all tree names from the JSON controller. + * + * @return An observable list of tree names. + */ + + fun getTreesList(): ObservableList? { + val controller = JsonController() + val treeNames = controller.getAllTrees() + val values = FXCollections.observableArrayList() + treeNames.forEach { + values.add(it) + } + return values + } + + /** + * Retrieves an AVL tree with the given name from the JSON controller. + * + * @param name The name of the tree to retrieve. + * @return The AVL tree with the given name, or null if it doesn't exist. + */ + + fun getTreeFromJson(name: String): AVLTree? { + val controller = JsonController() + return controller.getTree(name) + } + + /** + * Removes the AVL tree with the given name from the JSON controller. + * + * @param name The name of the tree to remove. + */ + + fun deleteTreeFromDB(name: String) { + JsonController().run { + removeTree(name) + } + } + + /** + * Saves the given AVL tree to the JSON controller with the given name. + * + * @param tree The AVL tree to save. + * @param treeName The name to use when saving the tree. + */ + + fun saveTree(tree: AVLTree, treeName: String) { + val controller = JsonController() + controller.saveTree(tree, treeName) + } + + /** + * Removes a node with the given value from the given AVL tree and redraws the tree on the given pane. + * + * @param value The value of the node to remove. + * @param tree The AVL tree to remove the node from. + * @param treePane The pane where the tree is to be drawn. + */ + + fun deleteNode(value: Int, tree: AVLTree, treePane: Pane) { + tree.remove(value) + drawTree(tree, treePane) + } +} diff --git a/app/src/main/kotlin/app/controller/BSTController.kt b/app/src/main/kotlin/app/controller/BSTController.kt new file mode 100644 index 0000000..b4ca510 --- /dev/null +++ b/app/src/main/kotlin/app/controller/BSTController.kt @@ -0,0 +1,215 @@ +package app.controller + +import bst.BSTree +import bst.db.controllers.SQLController +import bst.nodes.BSTNode +import javafx.collections.FXCollections.observableArrayList +import javafx.collections.ObservableList +import javafx.scene.control.Tooltip +import javafx.scene.layout.Pane +import javafx.scene.layout.StackPane +import javafx.scene.paint.Color +import javafx.scene.shape.Circle +import javafx.scene.shape.Line +import javafx.scene.text.Text +import javafx.scene.text.TextBoundsType +import tornadofx.Controller +import kotlin.math.min + +/** + * The BSTController class is responsible for managing binary search trees. + * + * It extends the Controller class and provides additional functionality for working with binary search trees. + */ + +class BSTController : Controller() { + + /** + * Determines whether a given string can be parsed as an integer. + * + * @param s The string to check. + * @return True if the string can be parsed as an integer, false otherwise. + */ + + fun isNumeric(s: String): Boolean { + return try { + s.toInt() + true + } catch (e: NumberFormatException) { + false + } + } + + /** + * Inserts a new node with the given key and value into the given binary search tree and redraws the tree on the given pane. + * + * @param tree The binary search tree to insert the node into. + * @param treePane The pane where the tree is to be drawn. + * @param key The key of the new node to insert. + * @param value The value of the new node to insert. + */ + + fun insertNode(tree: BSTree, treePane: Pane, key: Int, value: String) { + tree.insert(key, value) + drawTree(tree, treePane) + } + + /** + * Clears the given binary search tree and removes all nodes from the given pane. + * + * @param tree The binary search tree to clear. + * @param treePane The pane where the tree is to be drawn. + */ + + fun clearTree(tree: BSTree, treePane: Pane) { + tree.clear() + treePane.children.clear() + } + + /** + * Draws the given binary search tree on the given pane. + * + * @param tree The binary search tree to draw. + * @param treePane The pane where the tree is to be drawn. + */ + + fun drawTree(tree: BSTree, treePane: Pane) { + treePane.children.clear() + val root = tree.getRoot() + if (root != null) { + drawNode(root, treePane, treePane.width / 2.0, treePane.width / 2.0, 250.0) + } + } + + /** + * Draws a binary search tree node on a given tree pane at a specific position with a given offset. + * + * @param node The binary search tree node to draw. + * @param treePane The pane where the tree is to be drawn. + * @param x The x-coordinate of the node to draw. + * @param y The y-coordinate of the node to draw. + * @param offsetX The offset to apply to the x-coordinate of child nodes. + */ + + private fun drawNode(node: BSTNode, treePane: Pane, x: Double, y: Double, offsetX: Double) { + // Create a circle to represent the node + val circleRadius = 20.0 + val circle = Circle(circleRadius) + circle.fill = Color.WHITE + circle.stroke = Color.BLACK + + // Create a text label to display the node's key + val nodeText = Text(node.key.toString()) + nodeText.boundsType = TextBoundsType.VISUAL + + // Scale the text label to fit inside the circle + val scale = + min(circleRadius * 1.3 / nodeText.boundsInLocal.width, circleRadius * 1.3 / nodeText.boundsInLocal.height) + nodeText.scaleX = scale + nodeText.scaleY = scale + + // Combine the circle and text label into a StackPane + val nodeStackPane = StackPane(circle, nodeText) + nodeStackPane.relocate(x - circleRadius, y - circleRadius) + + // Add a tooltip to the StackPane to display the node's value + val tooltip = Tooltip("value: ${node.value}") + Tooltip.install(nodeStackPane, tooltip) + + // Add the StackPane to the tree pane + treePane.children.add(nodeStackPane) + + // If the node has a left child, draw it recursively + if (node.left != null) { + val leftX = x - offsetX + val leftY = y + 50 + val leftLine = Line(x, y + circleRadius, leftX, leftY - circleRadius) + treePane.children.add(leftLine) + drawNode(node.left!!, treePane, leftX, leftY, offsetX / 2.0) + } + + // If the node has a right child, draw it recursively + if (node.right != null) { + val rightX = x + offsetX + val rightY = y + 50 + val rightLine = Line(x, y + circleRadius, rightX, rightY - circleRadius) + treePane.children.add(rightLine) + drawNode(node.right!!, treePane, rightX, rightY, offsetX / 2.0) + } + } + + /** + * @return An ObservableList of tree names, or null if there are no trees in the database. + */ + + fun getTreesList(): ObservableList? { + // Creates a new SQLController object. + val controller = SQLController() + // Retrieves all tree names from the database. + val treeNames = controller.getAllTrees() + // Converts the list of tree names to an ObservableList. + val values = observableArrayList() + treeNames.forEach { + values.add(it) + } + // Returns the ObservableList of tree names. + return values + } + + /** + * Retrieves a binary search tree with the given name from the database. + * + * @param name The name of the binary search tree to retrieve. + * @return The binary search tree with the given name, or null if it does not exist in the database. + */ + + fun getTreeFromDB(name: String): BSTree? { + // Creates a new SQLController object. + val controller = SQLController() + // Retrieves the binary search tree with the given name from the database. + val tree = controller.getTree(name) + // Returns the binary search tree. + return tree + } + + /** + * Removes the binary search tree with the given name from the database. + * + * @param name The name of the binary search tree to remove. + */ + + fun deleteTreeFromDB(name: String) { + // Creates a new SQLController object and removes the binary search tree with the given name from the database. + SQLController().run { + removeTree(name) + } + } + + /** + * Saves a binary search tree to the database with the given name. + * + * @param tree The binary search tree to save. + * @param treeName The name to give the saved binary search tree. + */ + + fun saveTree(tree: BSTree, treeName: String) { + // Creates a new SQLController object and saves the binary search tree to the database with the given name. + val controller = SQLController() + controller.saveTree(tree, treeName) + } + + /** + * Removes the node with the given value from the binary search tree and redraws the tree on the given pane. + * + * @param value The value of the node to remove. + * @param tree The binary search tree to remove the node from. + * @param treePane The pane to redraw the tree on. + */ + + fun deleteNode(value: Int, tree: BSTree, treePane: Pane) { + // Removes the node with the given value from the binary search tree. + tree.remove(value) + // Redraws the binary search tree on the given pane. + drawTree(tree, treePane) + } +} diff --git a/app/src/main/kotlin/app/controller/RBTController.kt b/app/src/main/kotlin/app/controller/RBTController.kt new file mode 100644 index 0000000..2791662 --- /dev/null +++ b/app/src/main/kotlin/app/controller/RBTController.kt @@ -0,0 +1,200 @@ +package app.controller + +import bst.RedBlackTree +import bst.db.controllers.Neo4jController +import bst.nodes.RBTNode +import javafx.collections.FXCollections +import javafx.collections.ObservableList +import javafx.scene.control.Tooltip +import javafx.scene.layout.Pane +import javafx.scene.layout.StackPane +import javafx.scene.paint.Color +import javafx.scene.shape.Circle +import javafx.scene.shape.Line +import javafx.scene.text.Text +import javafx.scene.text.TextBoundsType +import tornadofx.Controller +import kotlin.math.min + +/** + * The RBTController class is responsible for managing red black trees. + * + * It extends the Controller class and provides additional functionality for working with RBT trees. + */ + +class RBTController : Controller() { + + /** + * Determines whether a given string can be parsed as an integer. + * + * @param s The string to check. + * @return True if the string can be parsed as an integer, false otherwise. + */ + + fun isNumeric(s: String): Boolean { + return try { + s.toInt() + true + } catch (e: NumberFormatException) { + false + } + } + + /** + * Inserts a new node with the given key and value into the Red-Black Tree and redraws the tree. + * @param tree The Red-Black Tree to insert the node into. + * @param treePane The Pane to draw the updated tree on. + * @param key The key of the new node to insert. + * @param value The value of the new node to insert. + */ + + fun insertNode(tree: RedBlackTree, treePane: Pane, key: Int, value: String) { + tree.insert(key, value) + drawTree(tree, treePane) + } + + /** + * Clears the Red-Black Tree and removes all nodes from the given Pane. + * @param tree The Red-Black Tree to clear. + * @param treePane The Pane to remove all nodes from. + */ + + fun clearTree(tree: RedBlackTree, treePane: Pane) { + tree.clear() + treePane.children.clear() + } + + /** + * Draws the Red-Black Tree on the given Pane. + * @param tree The Red-Black Tree to draw. + * @param treePane The Pane to draw the tree on. + * @throws NullPointerException if the root of the tree is null. + */ + + fun drawTree(tree: RedBlackTree, treePane: Pane) { + treePane.children.clear() + val root = tree.getRoot() + if (root != null) { + drawNode(root, treePane, treePane.width / 2.0, treePane.width / 2.0, 250.0) + } else { + throw NullPointerException("Root of the tree is null.") + } + } + + /** + * Draws a node of the Red-Black Tree on the given Pane, including a circle with the node's key and a tooltip with its value. + * If the node has a left child or a right child, it also draws a line to the child and recursively calls this function on the child. + * @param node The RBTNode to draw. + * @param treePane The Pane to draw the node on. + * @param x The x-coordinate of the center of the circle representing the node. + * @param y The y-coordinate of the center of the circle representing the node. + * @param offsetX The horizontal distance between the node and its child nodes. + */ + + private fun drawNode(node: RBTNode, treePane: Pane, x: Double, y: Double, offsetX: Double) { + // Create circle with node key + val circleRadius = 20.0 + val circle = Circle(circleRadius) + circle.fill = if (node.color == RBTNode.Color.RED) Color.RED else Color.BLACK + circle.stroke = Color.BLACK + + // Create text with node key + val nodeText = Text(node.key.toString()) + nodeText.fill = if (circle.fill == Color.RED) Color.BLACK else Color.WHITE + nodeText.boundsType = TextBoundsType.VISUAL + + // Scale text to fit inside circle + val scale = min(circleRadius * 1.3 / nodeText.boundsInLocal.width, circleRadius * 1.3 / nodeText.boundsInLocal.height) + nodeText.scaleX = scale + nodeText.scaleY = scale + + // Create StackPane with circle and text, and set its position + val nodeStackPane = StackPane(circle, nodeText) + nodeStackPane.relocate(x - circleRadius, y - circleRadius) + + // Add tooltip with node value to StackPane + val tooltip = Tooltip("value: ${node.value}") + Tooltip.install(nodeStackPane, tooltip) + + // Add StackPane to treePane + treePane.children.add(nodeStackPane) + + // Draw line to left child and recursively call drawNode on it + if (node.left != null) { + val leftX = x - offsetX + val leftY = y + 50 + val leftLine = Line(x, y + circleRadius, leftX, leftY - circleRadius) + treePane.children.add(leftLine) + drawNode(node.left!!, treePane, leftX, leftY, offsetX / 2.0) + } + + // Draw line to right child and recursively call drawNode on it + if (node.right != null) { + val rightX = x + offsetX + val rightY = y + 50 + val rightLine = Line(x, y + circleRadius, rightX, rightY - circleRadius) + treePane.children.add(rightLine) + drawNode(node.right!!, treePane, rightX, rightY, offsetX / 2.0) + } + } + + /** + * Gets a list of names of Red-Black Trees stored in a Neo4j database and returns it as an ObservableList of Strings. + * @return An ObservableList of Strings containing the names of Red-Black Trees stored in the Neo4j database. + */ + + fun getTreesList(): ObservableList? { + val controller = Neo4jController() + val treeNames = controller.getNames() + val values = FXCollections.observableArrayList() + treeNames.forEach { + values.add(it) + } + return values + } + + /** + * Retrieves a Red-Black Tree with the given name from a Neo4j database and returns it. + * @param name The name of the Red-Black Tree to retrieve. + * @return The Red-Black Tree with the given name, or null if it does not exist in the database. + */ + + fun getTreeFromNeo4j(name: String): RedBlackTree? { + val controller = Neo4jController() + return controller.getTree(name) + } + + /** + * Deletes a Red-Black Tree with the given name from a Neo4j database. + * @param name The name of the Red-Black Tree to delete. + */ + + fun deleteTreeFromDB(name: String) { + Neo4jController().run { + removeTree(name) + } + } + + /** + * Saves a Red-Black Tree to a Neo4j database with the given name. + * @param tree The Red-Black Tree to save. + * @param treeName The name to give the Red-Black Tree in the database. + */ + + fun saveTree(tree: RedBlackTree, treeName: String) { + val controller = Neo4jController() + controller.saveTree(tree, treeName) + } + + /** + * Removes a node with the given value from a Red-Black Tree, redraws the tree, and updates the given Pane. + * @param value The value of the node to remove. + * @param tree The Red-Black Tree to remove the node from. + * @param treePane The Pane to draw the updated tree on. + */ + + fun deleteNode(value: Int, tree: RedBlackTree, treePane: Pane) { + tree.remove(value) + drawTree(tree, treePane) + } +} diff --git a/app/src/main/kotlin/app/view/MainView.kt b/app/src/main/kotlin/app/view/MainView.kt new file mode 100644 index 0000000..437c8d4 --- /dev/null +++ b/app/src/main/kotlin/app/view/MainView.kt @@ -0,0 +1,27 @@ +package app.view +import app.view.treeView.BinarySearchTreeView +import tornadofx.View +import tornadofx.vbox + +/** + * Represents the main view of the application. + */ + +class MainView : View() { + + /** + * Represents the binary search tree view of the application. + */ + + private val tree: BinarySearchTreeView by inject() + + /** + * Represents the root node of the view. + */ + + override val root = vbox { + primaryStage.minWidth = 400.0 + primaryStage.minHeight = 600.0 + add(tree) + } +} diff --git a/app/src/main/kotlin/app/view/treeView/AVLTreeView.kt b/app/src/main/kotlin/app/view/treeView/AVLTreeView.kt new file mode 100644 index 0000000..9c0da18 --- /dev/null +++ b/app/src/main/kotlin/app/view/treeView/AVLTreeView.kt @@ -0,0 +1,168 @@ +package app.view.treeView + +import app.controller.AVLController +import bst.AVLTree +import javafx.beans.property.SimpleStringProperty +import javafx.scene.control.Alert +import javafx.scene.control.ScrollPane +import javafx.scene.layout.Pane +import tornadofx.ChangeListener +import tornadofx.View +import tornadofx.ViewTransition +import tornadofx.action +import tornadofx.alert +import tornadofx.button +import tornadofx.combobox +import tornadofx.field +import tornadofx.fieldset +import tornadofx.form +import tornadofx.hbox +import tornadofx.scrollpane +import tornadofx.seconds +import tornadofx.textfield +import tornadofx.vbox + +class AVLTreeView : View() { + private val controller: AVLController by inject() + private var tree = AVLTree() + private val treePane = Pane() + private val key = SimpleStringProperty() + private val value = SimpleStringProperty() + private var trees = controller.getTreesList() + private var selectedItem: String? = "" + private val treeName = SimpleStringProperty() + private val valueForDeletion = SimpleStringProperty() + + init { + // Add listeners to the width and height properties of the scene + val sizeChangeListener = ChangeListener { _, _, _ -> + resizeTreePane() + } + + primaryStage.widthProperty().addListener(sizeChangeListener) + primaryStage.heightProperty().addListener(sizeChangeListener) + } + + private fun resizeTreePane() { + treePane.prefWidthProperty().bind(root.widthProperty()) + treePane.prefHeightProperty().bind(root.heightProperty()) + controller.drawTree(tree, treePane) + } + + override val root = vbox { + hbox { + val availableTrees = combobox { + this@AVLTreeView.trees?.let { items.addAll(it) } + selectionModel.selectedItemProperty().addListener { _, _, newValue -> + this@AVLTreeView.selectedItem = newValue + } + } + + button("Select") { + action { + println("Selected item: $selectedItem") + val loadedTree = selectedItem?.let { controller.getTreeFromJson(it) } + if (loadedTree != null) { + tree = loadedTree + controller.drawTree(tree, treePane) + } + } + } + button("Delete") { + action { + selectedItem?.let { + controller.clearTree(tree, treePane) + controller.deleteTreeFromDB(it) + } + availableTrees.items.remove(selectedItem) + + println("Item deleted: $selectedItem") + } + } + + button("Clear") { + action { + controller.clearTree(tree, treePane) + } + } + form { + fieldset { + field("Key") { + textfield(key) + } + field("Value") { + textfield(value) + } + + button("Add") { + action { + if (key.value != null && value.value != null && controller.isNumeric(key.value)) { + controller.insertNode(tree, treePane, key.value.toInt(), value.value) + } else { + alert(type = Alert.AlertType.ERROR, header = "Insertion Error") + } + key.value = null + value.value = null + } + } + field("Key") { + textfield(valueForDeletion) + } + button("Delete") { + action { + if (controller.isNumeric(valueForDeletion.value)) { + controller.deleteNode(valueForDeletion.value.toInt(), tree, treePane) + } else { + alert(type = Alert.AlertType.ERROR, header = "Deletion Error") + } + } + } + + field("Input tree name") { + textfield(treeName) + } + button("Save tree") { + action { + if (tree.getRoot() != null) { + controller.saveTree(tree, treeName.value) + if (!availableTrees.items.contains(treeName.value)) { + availableTrees.items.add(treeName.value) + } + } else { + alert(type = Alert.AlertType.ERROR, header = "Can not save tree with empty root") + } + } + } + } + } + } + button("Binary Search Tree") { + action { + replaceWith( + BinarySearchTreeView::class, + ViewTransition.Slide(0.3.seconds, ViewTransition.Direction.LEFT) + ) + } + } + button("Red Black Tree") { + action { + replaceWith(RedBlackTreeView::class, ViewTransition.Slide(0.3.seconds, ViewTransition.Direction.LEFT)) + } + } + scrollpane { + style = "-fx-background-color: transparent; -fx-border-color: transparent; -fx-focus-color: transparent;" + content = treePane + isPannable = true + hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER + vbarPolicy = ScrollPane.ScrollBarPolicy.NEVER + + hvalue = 0.5 + vvalue = 0.5 + + treePane.apply { + minWidth = 5000.0 + minHeight = 5000.0 + } + } + } +} diff --git a/app/src/main/kotlin/app/view/treeView/BinarySearchTreeView.kt b/app/src/main/kotlin/app/view/treeView/BinarySearchTreeView.kt new file mode 100644 index 0000000..a274d7f --- /dev/null +++ b/app/src/main/kotlin/app/view/treeView/BinarySearchTreeView.kt @@ -0,0 +1,166 @@ +package app.view.treeView + +import app.controller.BSTController +import bst.BSTree +import javafx.beans.property.SimpleStringProperty +import javafx.scene.control.Alert +import javafx.scene.control.ScrollPane +import javafx.scene.layout.Pane +import tornadofx.ChangeListener +import tornadofx.View +import tornadofx.ViewTransition +import tornadofx.action +import tornadofx.alert +import tornadofx.button +import tornadofx.combobox +import tornadofx.field +import tornadofx.fieldset +import tornadofx.form +import tornadofx.hbox +import tornadofx.scrollpane +import tornadofx.seconds +import tornadofx.textfield +import tornadofx.vbox + +class BinarySearchTreeView : View() { + private val controller: BSTController by inject() + private var tree = BSTree() + private val treePane = Pane() + private val key = SimpleStringProperty() + private val value = SimpleStringProperty() + private var trees = controller.getTreesList() + private var selectedItem: String? = "" + private val treeName = SimpleStringProperty() + private val valueForDeletion = SimpleStringProperty() + + init { + // Add listeners to the width and height properties of the scene + val sizeChangeListener = ChangeListener { _, _, _ -> + resizeTreePane() + } + + primaryStage.widthProperty().addListener(sizeChangeListener) + primaryStage.heightProperty().addListener(sizeChangeListener) + } + + private fun resizeTreePane() { + treePane.prefWidthProperty().bind(root.widthProperty()) + treePane.prefHeightProperty().bind(root.heightProperty()) + controller.drawTree(tree, treePane) + } + + override val root = vbox { + hbox { + val availableTrees = combobox { + this@BinarySearchTreeView.trees?.let { items.addAll(it) } + selectionModel.selectedItemProperty().addListener { _, _, newValue -> + this@BinarySearchTreeView.selectedItem = newValue + } + } + + button("Select") { + action { + println("Selected item: $selectedItem") + val loadedTree = selectedItem?.let { controller.getTreeFromDB(it) } + if (loadedTree != null) { + tree = loadedTree + controller.drawTree(tree, treePane) + } + } + } + button("Delete") { + action { + selectedItem?.let { + controller.clearTree(tree, treePane) + controller.deleteTreeFromDB(it) + } + availableTrees.items.remove(selectedItem) + + println("Item deleted: $selectedItem") + } + } + + button("Clear") { + action { + controller.clearTree(tree, treePane) + } + } + form { + fieldset { + field("Key") { + textfield(key) + } + field("Value") { + textfield(value) + } + + button("Add") { + action { + if (key.value != null && value.value != null && controller.isNumeric(key.value)) { + controller.insertNode(tree, treePane, key.value.toInt(), value.value) + } else { + alert(type = Alert.AlertType.ERROR, header = "Insertion Error") + } + key.value = null + value.value = null + } + } + field("Key") { + textfield(valueForDeletion) + } + button("Delete") { + action { + if (controller.isNumeric(valueForDeletion.value)) { + controller.deleteNode(valueForDeletion.value.toInt(), tree, treePane) + } else { + alert(type = Alert.AlertType.ERROR, header = "Deletion Error") + } + } + } + + field("Input tree name") { + textfield(treeName) + } + button("Save tree") { + action { + if (tree.getRoot() != null) { + // tree.treeName = treeName.value + controller.saveTree(tree, treeName.value) + if (!availableTrees.items.contains(treeName.value)) { + availableTrees.items.add(treeName.value) + } + } else { + alert(type = Alert.AlertType.ERROR, header = "Can not save tree with empty root") + } + } + } + } + } + } + button("AVL Tree") { + action { + replaceWith(AVLTreeView::class, ViewTransition.Slide(0.3.seconds, ViewTransition.Direction.LEFT)) + } + } + button("Red Black Tree") { + action { + replaceWith(RedBlackTreeView::class, ViewTransition.Slide(0.3.seconds, ViewTransition.Direction.LEFT)) + } + } + scrollpane { + style = "-fx-background-color: transparent; -fx-border-color: transparent; -fx-focus-color: transparent;" + content = treePane + isPannable = true + hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER + vbarPolicy = ScrollPane.ScrollBarPolicy.NEVER + + hvalue = 0.5 + vvalue = 0.5 + + treePane.apply { + minWidth = 5000.0 + minHeight = 5000.0 + } + } + } +} diff --git a/app/src/main/kotlin/app/view/treeView/RedBlackTreeView.kt b/app/src/main/kotlin/app/view/treeView/RedBlackTreeView.kt new file mode 100644 index 0000000..11283a2 --- /dev/null +++ b/app/src/main/kotlin/app/view/treeView/RedBlackTreeView.kt @@ -0,0 +1,166 @@ +package app.view.treeView + +import app.controller.RBTController +import bst.RedBlackTree +import javafx.beans.property.SimpleStringProperty +import javafx.scene.control.Alert +import javafx.scene.control.ScrollPane +import javafx.scene.layout.Pane +import tornadofx.ChangeListener +import tornadofx.View +import tornadofx.ViewTransition +import tornadofx.action +import tornadofx.alert +import tornadofx.button +import tornadofx.combobox +import tornadofx.field +import tornadofx.fieldset +import tornadofx.form +import tornadofx.hbox +import tornadofx.scrollpane +import tornadofx.seconds +import tornadofx.textfield +import tornadofx.vbox + +class RedBlackTreeView : View() { + private val controller: RBTController by inject() + private var tree = RedBlackTree() + private val treePane = Pane() + private val key = SimpleStringProperty() + private val value = SimpleStringProperty() + private var trees = controller.getTreesList() + private var selectedItem: String? = "" + private val treeName = SimpleStringProperty() + private val valueForDeletion = SimpleStringProperty() + + init { + val sizeChangeListener = ChangeListener { _, _, _ -> + resizeTreePane() + } + + primaryStage.widthProperty().addListener(sizeChangeListener) + primaryStage.heightProperty().addListener(sizeChangeListener) + } + + private fun resizeTreePane() { + treePane.prefWidthProperty().bind(root.widthProperty()) + treePane.prefHeightProperty().bind(root.heightProperty()) + controller.drawTree(tree, treePane) + } + + override val root = vbox { + hbox { + val availableTrees = combobox { + this@RedBlackTreeView.trees?.let { items.addAll(it) } + selectionModel.selectedItemProperty().addListener { _, _, newValue -> + this@RedBlackTreeView.selectedItem = newValue + } + } + + button("Select") { + action { + println("Selected item: $selectedItem") + val loadedTree = selectedItem?.let { controller.getTreeFromNeo4j(it) } + if (loadedTree != null) { + tree = loadedTree + controller.drawTree(tree, treePane) + } + } + } + button("Delete") { + action { + selectedItem?.let { + controller.clearTree(tree, treePane) + controller.deleteTreeFromDB(it) + } + availableTrees.items.remove(selectedItem) + + println("Item deleted: $selectedItem") + } + } + + button("Clear") { + action { + controller.clearTree(tree, treePane) + } + } + form { + fieldset { + field("Key") { + textfield(key) + } + field("Value") { + textfield(value) + } + + button("Add") { + action { + if (key.value != null && value.value != null && controller.isNumeric(key.value)) { + controller.insertNode(tree, treePane, key.value.toInt(), value.value) + } else { + alert(type = Alert.AlertType.ERROR, header = "Insertion Error") + } + key.value = null + value.value = null + } + } + field("Value") { + textfield(valueForDeletion) + } + button("Delete") { + action { + if (controller.isNumeric(valueForDeletion.value)) { + controller.deleteNode(valueForDeletion.value.toInt(), tree, treePane) + } else { + alert(type = Alert.AlertType.ERROR, header = "Deletion Error") + } + } + } + + field("Input tree name") { + textfield(treeName) + } + button("Save tree") { + action { + if (tree.getRoot() != null) { +// tree.treeName = treeName.value + controller.saveTree(tree, treeName.value) + if (!availableTrees.items.contains(treeName.value)) { + availableTrees.items.add(treeName.value) + } + } else { + alert(type = Alert.AlertType.ERROR, header = "Can not save tree with empty root") + } + } + } + } + } + } + button("AVL Tree") { + action { + replaceWith(AVLTreeView::class, ViewTransition.Slide(0.3.seconds, ViewTransition.Direction.LEFT)) + } + } + + button("Binary Search Tree") { + action { + replaceWith(BinarySearchTreeView::class, ViewTransition.Slide(0.3.seconds, ViewTransition.Direction.LEFT)) + } + } + scrollpane { + style = "-fx-background-color: transparent; -fx-border-color: transparent; -fx-focus-color: transparent;" + content = treePane + isPannable = true + hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER + vbarPolicy = ScrollPane.ScrollBarPolicy.NEVER + + hvalue = 0.5 + vvalue = 0.5 + + treePane.apply { + minWidth = 5000.0 + minHeight = 5000.0 + } + } + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..1bd5c58 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,24 @@ +version: "3" +services: + local-database: + image: postgres:15.2 + env_file: + - postgres.env + ports: + - "5432:5432" + volumes: + - pg-volume:/var/lib/postgresql/data + neo4j: + image: neo4j:5.6.0 + container_name: neo4j + env_file: + - neo4j.env + ports: + - "7474:7474" + - "7687:7687" + volumes: + - neo4j-volume:/data + - neo4j-volume:/logs +volumes: + pg-volume: {} + neo4j-volume: {} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..ccebba7 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bdc9a83 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..79a61d4 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/json/test.json b/json/test.json new file mode 100644 index 0000000..3445cd5 --- /dev/null +++ b/json/test.json @@ -0,0 +1 @@ +{"treeName":"","rootNode":{"height":2,"key":234,"value":"gfh","left":{"height":1,"key":23,"value":"","right":{"height":0,"key":67,"value":"dgfh"}},"right":{"height":0,"key":324,"value":"fdsg"}}} \ No newline at end of file diff --git a/neo4j.env b/neo4j.env new file mode 100644 index 0000000..c3e61fd --- /dev/null +++ b/neo4j.env @@ -0,0 +1 @@ +NEO4J_AUTH=neo4j/password \ No newline at end of file diff --git a/postgres.env b/postgres.env new file mode 100644 index 0000000..ff9a750 --- /dev/null +++ b/postgres.env @@ -0,0 +1,3 @@ +POSTGRES_USER=test +POSTGRES_PASSWORD=test-test +POSTGRES_DB=test \ No newline at end of file diff --git a/readme_gif/example1.gif b/readme_gif/example1.gif new file mode 100644 index 0000000..4825c9a Binary files /dev/null and b/readme_gif/example1.gif differ diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..f368ad1 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,3 @@ +rootProject.name = "trees-3" +include("app") +include("trees") diff --git a/start-db.bat b/start-db.bat new file mode 100644 index 0000000..43793b2 --- /dev/null +++ b/start-db.bat @@ -0,0 +1,3 @@ +@echo off +set BASEDIR=%~dp0 +docker-compose --file "%BASEDIR%docker-compose.yml" up diff --git a/start-db.sh b/start-db.sh new file mode 100755 index 0000000..e3a97f1 --- /dev/null +++ b/start-db.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -e +BASEDIR=$(dirname "$0") +docker-compose --file "${BASEDIR}"/docker-compose.yml up diff --git a/trees/build.gradle.kts b/trees/build.gradle.kts new file mode 100644 index 0000000..a1cbaf8 --- /dev/null +++ b/trees/build.gradle.kts @@ -0,0 +1,61 @@ +plugins { + // Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin. + id("org.jetbrains.kotlin.jvm") version "1.8.10" + id("jacoco") + id("org.jetbrains.kotlin.plugin.noarg") version "1.8.20" + id("org.jetbrains.kotlin.plugin.serialization") version "1.8.10" +} + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + // Use the Kotlin JUnit 5 integration. + testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") + + // Use the JUnit 5 integration. + testImplementation("org.junit.jupiter:junit-jupiter-engine:5.9.2") + + implementation("io.github.microutils:kotlin-logging-jvm:2.0.11") + + implementation("org.slf4j", "slf4j-simple", "2.0.0") + + implementation("org.neo4j:neo4j-ogm-core:4.0.5") + runtimeOnly("org.neo4j:neo4j-ogm-bolt-driver:4.0.5") + + implementation("com.google.code.gson:gson:2.10.1") + + // Use JetBrains Exposed + implementation("org.jetbrains.exposed:exposed-core:0.40.1") + implementation("org.jetbrains.exposed:exposed-dao:0.40.1") + implementation("org.jetbrains.exposed:exposed-jdbc:0.40.1") + + implementation("org.xerial:sqlite-jdbc:3.41.2.1") + + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0") + implementation("org.postgresql:postgresql:42.5.4") +} + +tasks.test { + // Use JUnit Platform for unit tests. + finalizedBy(tasks.jacocoTestReport) // report is always generated after tests run + useJUnitPlatform() +} + +tasks.jacocoTestReport { + dependsOn(tasks.test) // tests are required to run before generating the report + reports { + xml.required.set(false) + html.required.set(true) + html.outputLocation.set(layout.buildDirectory.dir("reports/jacoco")) + csv.required.set(true) + csv.outputLocation.set(layout.buildDirectory.file("jacoco/report.csv")) + } +} + +noArg { + annotation("org.neo4j.ogm.annotation.NodeEntity") + annotation("org.neo4j.ogm.annotation.RelationshipEntity") +} diff --git a/trees/src/main/kotlin/bst/AVLTree.kt b/trees/src/main/kotlin/bst/AVLTree.kt new file mode 100644 index 0000000..4a3f512 --- /dev/null +++ b/trees/src/main/kotlin/bst/AVLTree.kt @@ -0,0 +1,173 @@ +package bst + +import bst.nodes.AVLNode +import kotlin.math.max + +/** + * This class represents an AVL tree data structure and extends the BalancingTree class. + * @param the type of keys in the AVL tree, must implement Comparable interface. + * @param the type of values in the AVL tree. + */ +class AVLTree, V>(@Transient val key: K? = null, @Transient val value: V? = null) : + BalancingTree>() { + + /** + * Initializes a new AVL node with the given key and value. + * @param key the key of the node. + * @param value the value of the node. + * @return a new AVL node with the given key and value. + */ + override fun initNode(key: K, value: V): AVLNode = AVLNode(key, value) + + /** + * Initializes an AVL tree with a root node if the key and value are not null. + * @param key the key of the root node. + * @param value the value of the root node. + */ + init { + if (key != null && value != null) { + rootNode = initNode(key, value) + } + } + + /** + * Inserts a new node with the given key and value into the AVL tree. + * @param node the current AVL node being examined, can be null. + * @param key the key of the new node to be inserted. + * @param value the value of the new node to be inserted. + * @return the AVL node that is the root of the subtree after insertion and rebalancing. + */ + override fun insertNode(node: AVLNode?, key: K, value: V): AVLNode { + if (node == null) return initNode(key, value) + if (key < node.key) { + node.left = insertNode(node.left, key, value) + } else if (key > node.key) { + node.right = insertNode(node.right, key, value) + } else { + node.value = value + } + updateHeight(node) + return balance(node) + } + + /** + * Gets the height of the given AVL node. + * @param node the AVL node whose height is to be returned, can be null. + * @return the height of the AVL node if it is not null, -1 otherwise. + */ + private fun getHeight(node: AVLNode?): Int { + return node?.height ?: -1 + } + + /** + * Updates the height of the given AVL node based on the heights of its left and right subtrees. + * @param node the AVL node whose height is to be updated. + */ + private fun updateHeight(node: AVLNode) { + node.height = max(getHeight(node.left), getHeight(node.right)) + 1 + } + + /** + * Gets the balance factor of the given AVL node. + * @param node the AVL node whose balance factor is to be returned, can be null. + * @return the balance factor of the AVL node if it is not null, 0 otherwise. + */ + private fun getBalanceFactor(node: AVLNode?): Int = when (node) { + null -> 0 + else -> getHeight(node.right) - getHeight(node.left) + } + + /** + * Balances the given AVL node by performing rotations if necessary. + * @param node the AVL node to be balanced. + * @return the AVL node that is the root of the subtree after balancing. + */ + private fun balance(node: AVLNode): AVLNode { + return when (getBalanceFactor(node)) { + -2 -> { + if (getBalanceFactor(node.left) == 1) { + node.left = node.left?.let { rotateLeft(it) } + } + return rotateRight(node) + } + + 2 -> { + if (getBalanceFactor(node.right) == -1) { + node.right = node.right?.let { rotateRight(it) } + } + return rotateLeft(node) + } + + else -> node + } + } + + /** + * Removes a node with the given key from the AVL tree starting at the given node. + * + * @param node The root node of the AVL tree or a subtree. + * @param key The key of the node to be removed. + * @return The root node of the AVL tree or a subtree after the removal. + */ + override fun removeNode(node: AVLNode?, key: K): AVLNode? { + if (node == null) return null + if (key < node.key) { + node.left = removeNode(node.left, key) + } else if (key > node.key) { + node.right = removeNode(node.right, key) + } else { + if (node.left == null) { + return node.right + } else if (node.right == null) { + return node.left + } else { + // Find the maximum node in the left subtree + val tmp: AVLNode = + findMax(node.left) ?: throw IllegalStateException("Left subtree must contain elements") + // Replace the node to be removed with the maximum node in the left subtree + node.key = tmp.key + node.value = tmp.value + // Remove the maximum node in the left subtree + node.left = removeNode(node.left, tmp.key) + } + } + // Update the height of the node after the removal + updateHeight(node) + // Balance the node after the removal + return balance(node) + } + + /** + * Rotates the given AVL node to the right. + * + * @param node The AVL node to be rotated. + * @return The AVL node that has been rotated. + * @throws IllegalStateException If the node's left child is null. + */ + override fun rotateRight(node: AVLNode): AVLNode { + val left = node.left ?: throw IllegalStateException("Node's left child cannot be null") + node.left = left.right + left.right = node + // Update the height of the nodes after the rotation + updateHeight(node) + updateHeight(left) + return left + } + + /** + * Rotates the given AVL node to the left. + * + * @param node The AVL node to be rotated. + * @return The AVL node that has been rotated. + * @throws IllegalStateException If the node's right child is null. + */ + override fun rotateLeft(node: AVLNode): AVLNode { + val right = node.right ?: throw IllegalStateException("Node's right child cannot be null") + node.right = right.left + right.left = node + // Update the height of the nodes after the rotation + updateHeight(node) + updateHeight(right) + return right + } +} diff --git a/trees/src/main/kotlin/bst/AbstractBST.kt b/trees/src/main/kotlin/bst/AbstractBST.kt new file mode 100644 index 0000000..551d3b8 --- /dev/null +++ b/trees/src/main/kotlin/bst/AbstractBST.kt @@ -0,0 +1,169 @@ +package bst + +import bst.nodes.BinaryNode + +/** + * An abstract class representing a binary search tree data structure. + * + * @param K the type of keys maintained by this binary search tree. + * @param V the type of mapped values. + * @param Self the type of the binary nodes in this binary search tree. + */ + +abstract class AbstractBST, V, Self : BinaryNode> : Tree { + + /** + * The name of this binary search tree. + */ + + var treeName: String = "" + + /** + * The root node of this binary search tree. + */ + + internal var rootNode: Self? = null + + /** + * Sets the name of this binary search tree. + * @param treeName the name of this binary search tree. + */ + + fun setName(treeName: String) { + this.treeName = treeName + } + + /** + * Returns the root node of this binary search tree. + * + * @return the root node of this binary search tree. + */ + + fun getRoot(): Self? = this.rootNode + + /** + * Clears this binary search tree by setting its root node to null. + */ + + fun clear() { + this.rootNode = null + } + + /** + * Initializes a new binary node with the given key and value\. + * @param key the key of the new node\. + * @param value the value of the new node\. + * @return a new binary node with the given key and value\. + */ + + protected abstract fun initNode(key: K, value: V): Self + + /** + * Inserts a new node with the given key and value into this binary search tree\. + * @param key the key of the new node\. + * @param value the value of the new node\. + */ + + override fun insert(key: K, value: V) { + rootNode = insertNode(rootNode, key, value) + } + + /** + * Inserts a new node with the given key and value into the binary search tree rooted at the given node\. + * + * @param node the root node of the binary search tree to insert the new node into\. + * @param key the key of the new node\. + * @param value the value of the new node\. + * @return the root node of the binary search tree after the new node has been inserted\. + */ + + protected open fun insertNode(node: Self?, key: K, value: V): Self { + if (node == null) return initNode(key, value) + if (key < node.key) { + node.left = insertNode(node.left, key, value) + } else if (key > node.key) { + node.right = insertNode(node.right, key, value) + } else { + node.value = value + } + return node + } + + /** + * Removes the node with the given key from the tree. + * @param key the key of the node to remove + */ + + override fun remove(key: K) { + rootNode = removeNode(rootNode, key) + } + + /** + * Recursively removes the node with the given key from the subtree rooted at the given node. + * @param node the root of the subtree to remove the node from + * @param key the key of the node to remove + * @return the root of the updated subtree + */ + + protected open fun removeNode(node: Self?, key: K): Self? { + if (node == null) return null + if (key < node.key) { + node.left = removeNode(node.left, key) + } else if (key > node.key) { + node.right = removeNode(node.right, key) + } else { + if (node.left == null) { + return node.right + } else if (node.right == null) { + return node.left + } else { + val tmp: Self = findMax(node.left)!! + node.key = tmp.key + node.value = tmp.value + node.left = removeNode(node.left, tmp.key) + } + } + return node + } + + /** + * Finds the value associated with the given key in the tree. + * @param key the key to search for in the tree + * @return the value associated with the given key if it exists, otherwise null + */ + + override fun find(key: K): V? = findNode(rootNode, key) + + /** + * Recursively searches for the value associated with the given key in the subtree rooted at the given node. + * @param node the root of the subtree to search in + * @param key the key to search for in the subtree + * @return the value associated with the given key if it exists in the subtree, otherwise null + */ + + private fun findNode(node: Self?, key: K): V? { + return if (node == null) { + null + } else if (key == node.key) { + node.value + } else { + if (key < node.key) { + findNode(node.left, key) + } else { + findNode(node.right, key) + } + } + } + + /** + * Recursively finds the node with the maximum key in the subtree rooted at the given node. + * @param node the root of the subtree to search in + * @return the node with the maximum key in the subtree, or null if the subtree is empty + */ + + protected fun findMax(node: Self?): Self? = when { + node == null -> null + node.right == null -> node + else -> findMax(node.right) + } +} diff --git a/trees/src/main/kotlin/bst/BSTree.kt b/trees/src/main/kotlin/bst/BSTree.kt new file mode 100644 index 0000000..b2b07a9 --- /dev/null +++ b/trees/src/main/kotlin/bst/BSTree.kt @@ -0,0 +1,35 @@ +package bst + +import bst.nodes.BSTNode + +/** + * A binary search tree implementation using a linked structure. + * @param K the type of keys stored in the tree, must implement Comparable + * @param V the type of values stored in the tree + * @param Self the type of the nodes in the tree, must extend BSTNode + */ + +class BSTree, V>(val key: K? = null, val value: V? = null) : + AbstractBST>() { + + /** + * Initializes a new node with the given key and value. + * @param key the key of the new node + * @param value the value of the new node + * @return the new node + */ + + override fun initNode(key: K, value: V): BSTNode = BSTNode(key, value) + + /** + * Constructs a new BSTree with the given key and value as the root node. + * @param key the key of the root node + * @param value the value of the root node + */ + + init { + if (key != null && value != null) { + rootNode = initNode(key, value) + } + } +} diff --git a/trees/src/main/kotlin/bst/BalancingTree.kt b/trees/src/main/kotlin/bst/BalancingTree.kt new file mode 100644 index 0000000..9e7a1c4 --- /dev/null +++ b/trees/src/main/kotlin/bst/BalancingTree.kt @@ -0,0 +1,32 @@ +package bst + +import bst.nodes.BinaryNode + +/** + * An abstract class representing a balancing tree data structure that extends the AbstractBST class. + * + * @param K the type of keys maintained by this balancing tree. + * @param V the type of mapped values. + * @param Self the type of the binary nodes in this balancing tree. + */ + +abstract class BalancingTree, V, Self : BinaryNode> : AbstractBST() { + + /** + * Rotates the given node to the left to rebalance the tree. + * + * @param node the node to rotate. + * @return the rotated node. + */ + + protected abstract fun rotateLeft(node: Self): Self + + /** + * Rotates the given node to the right to rebalance the tree. + * + * @param node the node to rotate. + * @return the rotated node. + */ + + protected abstract fun rotateRight(node: Self): Self +} diff --git a/trees/src/main/kotlin/bst/RedBlackTree.kt b/trees/src/main/kotlin/bst/RedBlackTree.kt new file mode 100644 index 0000000..02a2c5a --- /dev/null +++ b/trees/src/main/kotlin/bst/RedBlackTree.kt @@ -0,0 +1,325 @@ +package bst + +import bst.nodes.RBTNode + +/** + * RedBlackTree represents a red-black tree data structure and extends the BalancingTree class. + * + * @param The type of the keys in the tree, which must be comparable. + * @param The type of the values in the tree. + * @property key The key of the root node of the tree. + * @property value The value of the root node of the tree. + * @constructor Creates a new instance of the RedBlackTree class with the given key and value. + */ +class RedBlackTree, V>(@Transient val key: K? = null, @Transient val value: V? = null) : BalancingTree>() { + + /** + * Initializes a new Red-Black Tree node with the given key and value. + * + * @param key The key of the new node. + * @param value The value of the new node. + * @return The new node. + */ + override fun initNode(key: K, value: V): RBTNode = RBTNode(key, value) + + /** + * Initializes the root node of the tree with the given key and value if they are not null. + */ + init { + if (key != null && value != null) { + rootNode = initNode(key, value) + } + } + + /** + * Checks if the given Red-Black Tree node is red. + * + * @param node The node to check. + * @return true if the node is not null and has the color red, false otherwise. + */ + private fun isRed(node: RBTNode?): Boolean { + return node != null && node.color == RBTNode.Color.RED + } + + /** + * Inserts a new node with the given key and value into the Red-Black Tree. + * + * @param key The key of the new node. + * @param value The value of the new node. + */ + override fun insert(key: K, value: V) { + insertNode(key, value) + } + + /** + * Inserts a new node with the given key and value into the Red-Black Tree. + * + * @param key The key of the new node. + * @param value The value of the new node. + */ + private fun insertNode(key: K, value: V) { + if (rootNode == null) { + /* Empty tree case */ + rootNode = initNode(key, value) + rootNode?.color = RBTNode.Color.BLACK + return + } else { + val head = initNode(key, value) // False tree root + + var grandparent: RBTNode? = null + var helper: RBTNode = head + var parent: RBTNode? = null + + helper.right = rootNode + var iter: RBTNode? = helper.right + /* + true is for right child + false is for left child + */ + var direction = false + /* Last direction */ + var last = false + + // Search down the tree + while (true) { + if (iter == null) { + // Insert new node at the bottom + iter = initNode(key, value) + if (direction) parent?.right = iter else parent?.left = iter + } else if (isRed(iter.left) && isRed(iter.right)) { + // Color flip + iter.color = RBTNode.Color.RED + iter.left?.color = RBTNode.Color.BLACK + iter.right?.color = RBTNode.Color.BLACK + } + // Fix red violation + if (isRed(iter) && isRed(parent) && grandparent != null) { + val dir2 = helper.child(true) == grandparent + if (dir2) { + if (iter == parent?.child(last)) { + helper.right = rotate(grandparent, !last) + } else { + helper.right = doubleRotate(grandparent, !last) + } + } else { + if (iter == parent?.child(last)) { + helper.left = rotate(grandparent, !last) + } else { + helper.left = doubleRotate(grandparent, !last) + } + } + } + + // Stop if found + if (iter.key == key) { + iter.value = value + break + } + + last = direction + direction = iter.key < key + + // Update helpers + helper = grandparent ?: helper + grandparent = parent + parent = iter + iter = iter.child(direction) + } + + // Update root + rootNode = head.right + } + rootNode?.color = RBTNode.Color.BLACK + } + + /** + * Removes the node with the given key from the binary search tree. + * This function calls the removeNode function with the given key as its parameter. + * @param key the key of the node to be removed + */ + override fun remove(key: K) { + removeNode(key) + } + + /** + * Update the root of the Red-Black tree to the head child node and make the root black for simplified logic. + * @return 1 after the root is updated and colored black + * Removes the node with the given key from the binary search tree. + * @param key the key of the node to be removed + * @throws IllegalStateException if the root node of the tree is null + */ + + private fun removeNode(key: K): Int { + // Code implementation for removing node from the binary search tree + if (rootNode != null) { + /* + False tree root. + */ + val head = initNode( + key, + rootNode?.value + ?: throw IllegalStateException("Root of the tree cannot be null") + ) + var iter: RBTNode = head + var parent: RBTNode? = null + var grandparent: RBTNode? + var nodeToDelete: RBTNode? = null + /* + true is for right child + false is for left child + */ + var direction = true + + iter.right = rootNode + + /* + Search and push a red node down + to fix red violations as we go + */ + while (iter.child(direction) != null) { + val last = direction + + /* Move the helpers down */ + grandparent = parent + parent = iter + iter = parent.child(direction) ?: throw IllegalStateException("Parent node cannot be null") + direction = iter.key < key + + /* + Save the node with matching data and keep + going; we'll do removal tasks at the end + */ + if (iter.key == key) { + nodeToDelete = iter + } + /* Push the red node down with rotations and color flips */ + if (!isRed(iter) && !isRed(iter.child(direction))) { + if (isRed(iter.child(!direction))) { + if (last) { + parent.right = rotate(iter, direction) + } else { + parent.left = rotate(iter, direction) + } + parent = parent.child(last) + } else if (!isRed(iter.child(!direction))) { + val sibling = parent.child(!last) + + if (sibling != null) { + if (!isRed(sibling.child(!last)) && !isRed(sibling.child(last))) { + /* Color flip */ + parent.color = RBTNode.Color.BLACK + sibling.color = RBTNode.Color.RED + iter.color = RBTNode.Color.RED + } else { + val direction2 = ( + grandparent?.right + ?: throw IllegalStateException("Grandparent node cannot be null") + ) == parent + + if (isRed(sibling.child(last))) { + if (direction2) { + grandparent.right = doubleRotate(parent, last) + } else { + grandparent.left = doubleRotate(parent, last) + } + } else if (isRed(sibling.child(!last))) { + if (direction2) { + grandparent.right = rotate(parent, last) + } else { + grandparent.left = rotate(parent, last) + } + } + /* Ensure correct coloring */ + iter.color = RBTNode.Color.RED + grandparent.child(direction2)?.color = RBTNode.Color.RED + grandparent.child(direction2)?.left?.color = RBTNode.Color.BLACK + grandparent.child(direction2)?.right?.color = RBTNode.Color.BLACK + } + } + } + } + } + + /* Replace and remove the saved node */ + if (nodeToDelete != null) { + nodeToDelete.key = iter.key + nodeToDelete.value = iter.value + if (parent?.right == iter) { + parent.right = iter.child(iter.left == null) + } else { + parent?.left = iter.child(iter.left == null) + } + } + + /* Update the root (it may be different) */ + rootNode = head.child(true) + + /* Make the root black for simplified logic */ + rootNode?.color = RBTNode.Color.BLACK + } + return 1 + } + + /** + * Performs a single rotation on the given node in the specified direction. + * @param node the node to be rotated + * @param dir the direction of the rotation (true for right, false for left) + * @return the child node after the rotation + */ + + private fun rotate(node: RBTNode, dir: Boolean): RBTNode { + // Code implementation for performing a single rotation on the given node + val childNode: RBTNode = if (dir) { + rotateRight(node) + } else { + rotateLeft(node) + } + node.color = RBTNode.Color.RED + childNode.color = RBTNode.Color.BLACK + return childNode + } + + /** + * Performs a double rotation on the given node in the specified direction. + * @param node the node to be double rotated + * @param dir the direction of the double rotation (true for right, false for left) + * @return the child node after the double rotation + */ + + private fun doubleRotate(node: RBTNode, dir: Boolean): RBTNode { + if (dir) { + node.left = node.left?.let { rotate(it, false) } + } else { + node.right = node.right?.let { rotate(it, true) } + } + return rotate(node, dir) + } + + /** + * Rotates the given node to the left to rebalance the tree. + * @param node the node to be rotated to the left + * @return the new node after the rotation + * @throws IllegalStateException if the node's right child is null + */ + + override fun rotateLeft(node: RBTNode): RBTNode { + val right = node.right ?: throw IllegalStateException("Node's right child cannot be null") + node.right = right.left + right.left = node + return right + } + + /** + * Rotates the given node to the right to rebalance the tree. + * @param node the node to be rotated to the right + * @return the new node after the rotation + * @throws IllegalStateException if the node's left child is null + */ + + override fun rotateRight(node: RBTNode): RBTNode { + val left = node.left ?: throw IllegalStateException("Node's left child cannot be null") + node.left = left.right + left.right = node + return left + } +} diff --git a/trees/src/main/kotlin/bst/Tree.kt b/trees/src/main/kotlin/bst/Tree.kt new file mode 100644 index 0000000..af98e87 --- /dev/null +++ b/trees/src/main/kotlin/bst/Tree.kt @@ -0,0 +1,33 @@ +package bst + +/** + * An interface for a binary search tree. + * @param K the type of keys stored in the tree, must implement Comparable + * @param V the type of values stored in the tree + */ + +interface Tree, V> { + + /** + * Inserts a key-value pair into the tree. + * @param key the key to insert + * @param value the value to associate with the key + */ + + fun insert(key: K, value: V) + + /** + * Removes the key-value pair with the given key from the tree. + * @param key the key of the pair to remove + */ + + fun remove(key: K) + + /** + * Finds the value associated with the given key in the tree. + * @param key the key to search for in the tree + * @return the value associated with the given key if it exists, otherwise null + */ + + fun find(key: K): V? +} diff --git a/trees/src/main/kotlin/bst/db/controllers/Controller.kt b/trees/src/main/kotlin/bst/db/controllers/Controller.kt new file mode 100644 index 0000000..e2b19e2 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/controllers/Controller.kt @@ -0,0 +1,35 @@ +package bst.db.controllers + +import bst.AbstractBST +import bst.nodes.BinaryNode + +/** + * The Controller interface defines the operations for managing binary search trees (BSTs) in the database. + * + * @param N the type of BinaryNode used in the BST + * @param T the type of AbstractBST implementation + */ +interface Controller, T : AbstractBST> { + /** + * Saves a BST with the specified name to the database. + * + * @param tree the BST to save + * @param treeName the name of the BST + */ + fun saveTree(tree: T, treeName: String) + + /** + * Retrieves a BST with the specified name from the database. + * + * @param treeName the name of the BST to retrieve + * @return the retrieved BST object, or null if the BST is not found + */ + fun getTree(treeName: String): T? + + /** + * Removes a BST with the specified name from the database. + * + * @param treeName the name of the BST to remove + */ + fun removeTree(treeName: String) +} diff --git a/trees/src/main/kotlin/bst/db/controllers/JsonController.kt b/trees/src/main/kotlin/bst/db/controllers/JsonController.kt new file mode 100644 index 0000000..c95d0d1 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/controllers/JsonController.kt @@ -0,0 +1,77 @@ +package bst.db.controllers + +import bst.AVLTree +import bst.nodes.AVLNode +import com.google.gson.Gson +import java.io.File +import java.io.FileReader +import java.io.FileWriter + +/** + * The JsonController class implements the Controller interface for managing AVL trees stored in JSON files. + */ +class JsonController : Controller, AVLTree> { + /** + * The path to the folder where JSON files are stored. + */ + val folderPath = "json" + + /** + * Saves an AVL tree with the specified name to a JSON file. + * + * @param tree the AVL tree to save + * @param treeName the name of the tree + */ + override fun saveTree(tree: AVLTree, treeName: String) { + val gson = Gson() + try { + val writer = FileWriter("${this.folderPath}/$treeName.json") + gson.toJson(tree, writer) + writer.close() + } catch (e: Exception) { + println("Write error") + } + } + + /** + * Retrieves an AVL tree with the specified name from a JSON file. + * + * @param treeName the name of the tree to retrieve + * @return the retrieved AVL tree object, or null if the tree is not found or an error occurs + */ + override fun getTree(treeName: String): AVLTree? { + val gson = Gson() + return try { + val reader = FileReader("${this.folderPath}/$treeName.json") + val tree = gson.fromJson(reader, AVLTree()::class.java) + reader.close() + tree + } catch (e: Exception) { + println("Read error") + null + } + } + + /** + * Removes an AVL tree with the specified name by deleting the corresponding JSON file. + * + * @param treeName the name of the tree to remove + */ + override fun removeTree(treeName: String) { + File("${this.folderPath}/$treeName.json").delete() + } + + /** + * Retrieves a list of names of all available AVL trees stored as JSON files. + * + * @return a list of tree names + */ + fun getAllTrees(): List { + val jsonFiles = File(folderPath).listFiles { file -> file.extension == "json" } + val jsonNames = mutableListOf() + jsonFiles?.forEach { file -> + jsonNames.add(file.name.removeSuffix(".json")) + } + return jsonNames + } +} diff --git a/trees/src/main/kotlin/bst/db/controllers/Neo4jController.kt b/trees/src/main/kotlin/bst/db/controllers/Neo4jController.kt new file mode 100644 index 0000000..003e2af --- /dev/null +++ b/trees/src/main/kotlin/bst/db/controllers/Neo4jController.kt @@ -0,0 +1,212 @@ +package bst.db.controllers + +import bst.RedBlackTree +import bst.db.models.neo4j.TreeEntity +import bst.db.models.neo4j.TreeNodeEntity +import bst.db.serializeClasses.SerializableNode +import bst.db.serializeClasses.SerializableTree +import bst.nodes.RBTNode +import bst.nodes.RBTNode.Color +import org.neo4j.ogm.config.Configuration +import org.neo4j.ogm.session.SessionFactory + +/** + * Controller class for managing Red-Black Trees stored in a Neo4j database. + */ +class Neo4jController : Controller, RedBlackTree> { + /** + * The Neo4j database configuration. + */ + private val config = Configuration.Builder() + .uri("bolt://localhost") + .credentials("neo4j", "password") + .build() + + /** + * The session factory for creating database sessions. + */ + private val sessionFactory = SessionFactory(config, "bst") + + /** + * The database session. + */ + private val session = sessionFactory.openSession() + + /** + * Converts an RBTNode object to a SerializableNode object. + * + * @return the SerializableNode representation of the RBTNode + */ + private fun RBTNode<*, *>?.toSerializableNode(): SerializableNode? { + if (this == null) { + return null + } + return SerializableNode( + key.toString(), + value.toString(), + 0.0, + 0.0, + color.toString(), + left?.toSerializableNode(), + right?.toSerializableNode() + ) + } + + /** + * Converts a RedBlackTree object to a SerializableTree object. + * + * @param treeName the name of the tree + * @return the SerializableTree representation of the RedBlackTree + */ + private fun RedBlackTree<*, *>.toSerializableTree(treeName: String): SerializableTree { + return SerializableTree(treeName, rootNode?.toSerializableNode()) + } + + /** + * Converts a TreeNodeEntity object to a SerializableNode object. + * + * @return the SerializableNode representation of the TreeNodeEntity + */ + private fun TreeNodeEntity.toSerializableNode(): SerializableNode { + return SerializableNode(key, value, x, y, metadata, left?.toSerializableNode(), right?.toSerializableNode()) + } + + /** + * Converts a TreeEntity object to a SerializableTree object. + * + * @return the SerializableTree representation of the TreeEntity + */ + private fun TreeEntity.toSerializableTree(): SerializableTree { + return SerializableTree(treeName, rootNode?.toSerializableNode()) + } + + /** + * Converts a SerializableNode object to a TreeNodeEntity object. + * + * @return the TreeNodeEntity representation of the SerializableNode + */ + private fun SerializableNode.toNodeEntity(): TreeNodeEntity { + return TreeNodeEntity(key, value, x, y, metadata, leftNode?.toNodeEntity(), rightNode?.toNodeEntity()) + } + + /** + * Converts a SerializableTree object to a TreeEntity object. + * + * @return the TreeEntity representation of the SerializableTree + */ + private fun SerializableTree.toTreeEntity(): TreeEntity { + return TreeEntity(treeName, rootNode?.toNodeEntity()) + } + + /** + * Deserializes a SerializableNode object to an RBTNode object. + * + * @return the deserialized RBTNode object + */ + private fun deserializeNode(node: SerializableNode?): RBTNode? { + node ?: return null + val rbtNode = RBTNode( + key = node.key.toInt(), + value = node.value, + color = deserializeMetadata(node.metadata) + ) + rbtNode.left = deserializeNode(node.leftNode) + rbtNode.right = deserializeNode(node.rightNode) + return rbtNode + } + + /** + * Deserializes a SerializableTree object to a RedBlackTree object. + * + * @return the deserialized RedBlackTree object + */ + private fun deserializeTree(tree: SerializableTree): RedBlackTree { + val rbTree = RedBlackTree() + rbTree.rootNode = deserializeNode(tree.rootNode) + return rbTree + } + + /** + * Deserializes a metadata string to a Color enum. + * + * @return the deserialized Color enum + * @throws NoSuchFieldException if the metadata does not match any Color values + */ + private fun deserializeMetadata(metadata: String?): Color { + return when (metadata) { + "RED" -> Color.RED + "BLACK" -> Color.BLACK + else -> throw NoSuchFieldException("Node's color must be either RED or BLACK") + } + } + + /** + * Saves a RedBlackTree to the Neo4j database with the specified name. + * + * @param tree the RedBlackTree to save + * @param treeName the name of the tree + */ + override fun saveTree(tree: RedBlackTree, treeName: String) { + removeTree(treeName) + val entityTree = tree.toSerializableTree(treeName).toTreeEntity() + entityTree.treeName = treeName + session.save(entityTree) + session.query( + "MATCH (n: BinaryNode) WHERE NOT (n)--() DELETE (n)", + mapOf() + ) + } + + /** + * Removes a RedBlackTree with the specified name from the Neo4j database. + * + * @param treeName the name of the tree to remove + */ + override fun removeTree(treeName: String) { + session.query( + "MATCH (n)-[r *0..]->(m) " + "WHERE n.treeName = \$treeName DETACH DELETE m", + mapOf("treeName" to treeName) + ) + } + + /** + * Retrieves a RedBlackTree with the specified name from the Neo4j database. + * + * @param treeName the name of the tree to retrieve + * @return the retrieved RedBlackTree object, or null if the tree is not found + */ + override fun getTree(treeName: String): RedBlackTree? { + val tree = loadTree(treeName) + return tree?.let { deserializeTree(it.toSerializableTree()) } + } + + /** + * Loads a TreeEntity from the Neo4j database with the specified name. + * + * @param treeName the name of the tree to load + * @return the loaded TreeEntity object, or null if the tree is not found + */ + private fun loadTree(treeName: String): TreeEntity? { + return session.queryForObject( + TreeEntity::class.java, + "MATCH (n)-[r *1..]-(m) " + "WHERE n.treeName = \$treeName RETURN n, r, m", + mapOf("treeName" to treeName) + ) ?: null + } + + /** + * Closes the Neo4j session and session factory. + */ + fun close() { + session.clear() + sessionFactory.close() + } + + /** + * Retrieves the names of all the trees stored in the Neo4j database. + * + * @return a list of tree names + */ + fun getNames() = session.query("MATCH (n: TreeEntity) RETURN n.treeName", mapOf()) + .flatMap { it.values.map { value -> value.toString() } } +} diff --git a/trees/src/main/kotlin/bst/db/controllers/SQLController.kt b/trees/src/main/kotlin/bst/db/controllers/SQLController.kt new file mode 100644 index 0000000..49f7724 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/controllers/SQLController.kt @@ -0,0 +1,255 @@ +package bst.db.controllers + +import bst.BSTree +import bst.db.models.sql.Node +import bst.db.models.sql.Nodes +import bst.db.models.sql.Tree +import bst.db.models.sql.Trees +import bst.db.serializeClasses.SerializableNode +import bst.db.serializeClasses.SerializableTree +import bst.nodes.BSTNode +import org.jetbrains.exposed.exceptions.ExposedSQLException +import org.jetbrains.exposed.sql.Database +import org.jetbrains.exposed.sql.SchemaUtils +import org.jetbrains.exposed.sql.StdOutSqlLogger +import org.jetbrains.exposed.sql.addLogger +import org.jetbrains.exposed.sql.selectAll +import org.jetbrains.exposed.sql.transactions.transaction + +/** + * A controller class for interacting with a binary search tree (BST) stored in an SQL database. + * It provides methods for saving, retrieving, and removing BSTs from the database. + */ +class SQLController : Controller, BSTree> { + /** + * Connects to the SQL database and creates the required tables if they don't exist. + */ + private fun connectDB() { + Database.connect( + "jdbc:postgresql://localhost:5432/test", + driver = "org.postgresql.Driver", + user = "test", + password = "test-test" + ) + createTables() + } + + /** + * Removes a tree from the database with the specified name. + * + * @param treeName the name of the tree to remove + */ + override fun removeTree(treeName: String) { + transaction { + try { + Tree.find { (Trees.name eq treeName) } + .firstOrNull()?.delete() + } catch (e: ExposedSQLException) { + println("Tree does not exists") + } + } + } + + /** + * Serializes a BSTNode object into a SerializableNode object. + * + * @param node the BSTNode to serialize + * @return the serialized SerializableNode object + */ + private fun serializeNode(node: BSTNode?): SerializableNode? { + return if (node == null) { + null + } else { + val serializableNode = SerializableNode( + key = node.key.toString(), + value = node.value, + leftNode = null, + rightNode = null + ) + serializableNode.rightNode = serializeNode(node.right) + serializableNode.leftNode = serializeNode(node.left) + serializableNode + } + } + + /** + * Serializes a BSTree object into a SerializableTree object. + * + * @param tree the BSTree to serialize + * @param treeName the name of the tree + * @return the serialized SerializableTree object + */ + private fun serializeTree(tree: BSTree, treeName: String): SerializableTree? { + return tree.rootNode?.let { serializeNode(it) } + ?.let { SerializableTree(treeName = treeName, rootNode = it) } + } + + /** + * Creates the required tables in the database if they don't exist. + */ + private fun createTables() { + transaction { + SchemaUtils.create(Trees) + SchemaUtils.create(Nodes) + } + } + + /** + * Converts a SerializableNode object into a Node object and associates it with the specified Tree object. + * + * @param treeDao the Tree object to associate the Node with + * @return the created Node object + */ + private fun SerializableNode.toNodeDao(treeDao: Tree): Node { + return Node.new { + key = this@toNodeDao.key + value = this@toNodeDao.value + x = this@toNodeDao.x + y = this@toNodeDao.y + left = this@toNodeDao.leftNode?.toNodeDao(treeDao) + right = this@toNodeDao.rightNode?.toNodeDao(treeDao) + tree = treeDao + } + } + + /** + * Saves a BSTree object to the database with the specified name. + * + * @param tree the BSTree to save + * @param treeName the name of the tree + */ + override fun saveTree(tree: BSTree, treeName: String) { + connectDB() + removeTree(treeName) + val serializedTree = serializeTree(tree, treeName) + transaction { + addLogger(StdOutSqlLogger) + createTables() + val daoTree = Tree.new { + if (serializedTree != null) name = serializedTree.treeName + } + daoTree.rootNode = serializedTree?.rootNode?.toNodeDao(daoTree) + } + } + + /** + * Converts a Node object into a SerializableNode object. + * + * @param treeDao the associated Tree object + * @return the serialized SerializableNode object + */ + private fun Node.getSerializedNode(treeDao: Tree): SerializableNode { + return SerializableNode( + this@getSerializedNode.key, + this@getSerializedNode.value, + this@getSerializedNode.x, + this@getSerializedNode.y, + null, + this@getSerializedNode.left?.getSerializedNode(treeDao), + this@getSerializedNode.right?.getSerializedNode(treeDao) + ) + } + + /** + * Finds a SerializableTree object with the specified name in the database. + * + * @param treeName the name of the tree to find + * @return the found SerializableTree object, or null if not found + */ + private fun findTree(treeName: String): SerializableTree? { + connectDB() + val treeDAO = Tree.find { Trees.name eq treeName }.firstOrNull() ?: return null + return treeDAO.rootNode?.getSerializedNode(treeDAO)?.let { + SerializableTree( + treeName, + it + ) + } + } + + /** + * Checks if a given string is numeric. + * + * @param s the string to check + * @return true if the string is numeric, false otherwise + */ + private fun isNumeric(s: String): Boolean { + return try { + s.toInt() + true + } catch (e: NumberFormatException) { + false + } + } + + /** + * Deserializes a SerializableNode object with integer keys into a BSTNode object. + * + * @param node the SerializableNode to deserialize + * @return the deserialized BSTNode object + */ + private fun deserializeNodeDoubleKey(node: SerializableNode?): BSTNode? { + return if (node == null) { + null + } else { + val deserializableNode = BSTNode(key = node.key.toInt(), value = node.value) + deserializableNode.right = deserializeNodeDoubleKey(node.rightNode) + deserializableNode.left = deserializeNodeDoubleKey(node.leftNode) + deserializableNode + } + } + + /** + * Deserializes a SerializableTree object into a BSTree object. + * The deserialization process converts the SerializableTree's root node + * and its children SerializableNodes into BSTNodes. + * + * @param tree the SerializableTree to deserialize + * @return the deserialized BSTree object, or null if the serialization is invalid + */ + private fun deserializeTree(tree: SerializableTree?): BSTree? { + if (tree != null) { + if (isNumeric(tree.rootNode!!.key)) { + val rootNode = deserializeNodeDoubleKey(tree.rootNode) + val deserializedTree: BSTree = BSTree(rootNode?.key, rootNode?.value) + deserializedTree.rootNode = rootNode + return deserializedTree + } + } + return null + } + + /** + * Retrieves a BSTree object from the database with the specified name. + * The retrieval process involves finding the SerializableTree with the given name, + * deserializing it, and converting it into a BSTree. + * + * @param treeName the name of the tree to retrieve + * @return the retrieved BSTree object, or null if the tree is not found in the database + */ + override fun getTree(treeName: String): BSTree? { + var deserializedTree: SerializableTree? = null + transaction { + deserializedTree = findTree(treeName) + } + return deserializeTree(deserializedTree) + } + + /** + * Retrieves the names of all the trees stored in the database. + * + * @return a list of tree names + */ + fun getAllTrees(): List { + val notes = mutableListOf() + connectDB() + transaction { + Trees.selectAll().forEach { + val name = it[Trees.name] + notes.add(name) + } + } + + return notes + } +} diff --git a/trees/src/main/kotlin/bst/db/models/neo4j/TreeEntity.kt b/trees/src/main/kotlin/bst/db/models/neo4j/TreeEntity.kt new file mode 100644 index 0000000..abb9e6d --- /dev/null +++ b/trees/src/main/kotlin/bst/db/models/neo4j/TreeEntity.kt @@ -0,0 +1,22 @@ +package bst.db.models.neo4j + +import org.neo4j.ogm.annotation.GeneratedValue +import org.neo4j.ogm.annotation.Id +import org.neo4j.ogm.annotation.NodeEntity + +/** + * Represents a tree entity in the Neo4j database. + * + * @property treeName The name of the tree. + * @property rootNode The root node of the tree. + * @property id The unique identifier of the tree entity. + */ +@NodeEntity +class TreeEntity( + var treeName: String = "", + var rootNode: TreeNodeEntity? = null +) { + @Id + @GeneratedValue + var id: Long? = null +} diff --git a/trees/src/main/kotlin/bst/db/models/neo4j/TreeNodeEntity.kt b/trees/src/main/kotlin/bst/db/models/neo4j/TreeNodeEntity.kt new file mode 100644 index 0000000..0c387a9 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/models/neo4j/TreeNodeEntity.kt @@ -0,0 +1,36 @@ +package bst.db.models.neo4j + +import org.neo4j.ogm.annotation.GeneratedValue +import org.neo4j.ogm.annotation.Id +import org.neo4j.ogm.annotation.NodeEntity +import org.neo4j.ogm.annotation.Relationship + +/** + * Represents a node entity in a binary search tree stored in the Neo4j database. + * + * @property key The key of the node. + * @property value The value associated with the node. + * @property x The x-coordinate of the node in a visualization (default is 0.0). + * @property y The y-coordinate of the node in a visualization (default is 0.0). + * @property metadata Additional metadata associated with the node. + * @property left The left child node of the current node. + * @property right The right child node of the current node. + * @property id The unique identifier of the node entity. + */ +@NodeEntity +class TreeNodeEntity( + val key: String, + val value: String, + val x: Double = 0.0, + val y: Double = 0.0, + var metadata: String? = null, + @Relationship(type = "LEFT") var left: TreeNodeEntity? = null, + @Relationship(type = "RIGHT") var right: TreeNodeEntity? = null +) { + /** + * The unique identifier of the node entity. + */ + @Id + @GeneratedValue + var id: Long? = null +} diff --git a/trees/src/main/kotlin/bst/db/models/sql/Node.kt b/trees/src/main/kotlin/bst/db/models/sql/Node.kt new file mode 100644 index 0000000..5ce7c42 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/models/sql/Node.kt @@ -0,0 +1,34 @@ +package bst.db.models.sql + +import org.jetbrains.exposed.dao.IntEntity +import org.jetbrains.exposed.dao.IntEntityClass +import org.jetbrains.exposed.dao.id.EntityID + +/** + * Represents a node entity in a binary search tree stored in the SQL database. + * + * @property id The unique identifier of the node entity. + * @property key The key of the node. + * @property value The value associated with the node. + * @property x The x-coordinate of the node in a visualization. + * @property y The y-coordinate of the node in a visualization. + * @property left The left child node of the current node. + * @property right The right child node of the current node. + * @property tree The tree to which the node belongs. + */ +class Node(id: EntityID) : IntEntity(id) { + companion object : IntEntityClass(Nodes) + + var key by Nodes.key + var value by Nodes.value + var x by Nodes.x + var y by Nodes.y + var left by Node optionalReferencedOn Nodes.left + var right by Node optionalReferencedOn Nodes.right + var tree by Tree referencedOn Nodes.tree + + /** + * Returns a string representation of the node. + */ + override fun toString(): String = "Node(key = $key, value=$value, x=$x, y=$y, left=$left, right=$right, tree=$tree)" +} diff --git a/trees/src/main/kotlin/bst/db/models/sql/Nodes.kt b/trees/src/main/kotlin/bst/db/models/sql/Nodes.kt new file mode 100644 index 0000000..2faa278 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/models/sql/Nodes.kt @@ -0,0 +1,25 @@ +package bst.db.models.sql + +import org.jetbrains.exposed.dao.id.IntIdTable +import org.jetbrains.exposed.sql.ReferenceOption + +/** + * Represents the database table for storing node entities in a binary search tree. + * + * @property key Column for the key of the node. + * @property value Column for the value associated with the node. + * @property x Column for the x-coordinate of the node in a visualization, with a default value of 0.0. + * @property y Column for the y-coordinate of the node in a visualization, with a default value of 0.0. + * @property left Column for the left child node reference, allowing null values. + * @property right Column for the right child node reference, allowing null values. + * @property tree Column for the tree reference to which the node belongs, with CASCADE delete behavior. + */ +object Nodes : IntIdTable("nodes") { + val key = varchar("key", length = 256) + val value = varchar("value", length = 256) + val x = double("x_coordinate").default(0.0) + val y = double("y_coordinate").default(0.0) + val left = reference("left", Nodes).nullable() + val right = reference("right", Nodes).nullable() + val tree = reference("tree", Trees, onDelete = ReferenceOption.CASCADE) +} diff --git a/trees/src/main/kotlin/bst/db/models/sql/Tree.kt b/trees/src/main/kotlin/bst/db/models/sql/Tree.kt new file mode 100644 index 0000000..6160f0a --- /dev/null +++ b/trees/src/main/kotlin/bst/db/models/sql/Tree.kt @@ -0,0 +1,24 @@ +package bst.db.models.sql + +import org.jetbrains.exposed.dao.IntEntity +import org.jetbrains.exposed.dao.IntEntityClass +import org.jetbrains.exposed.dao.id.EntityID + +/** + * Represents a tree entity in the SQL database. + * + * @property id The unique identifier of the tree entity. + * @property name The name of the tree. + * @property rootNode The root node of the tree, allowing null values. + */ +class Tree(id: EntityID) : IntEntity(id) { + companion object : IntEntityClass(Trees) + + var name by Trees.name + var rootNode by Node optionalReferencedOn Trees.rootNode + + /** + * Returns a string representation of the tree. + */ + override fun toString(): String = "Node(key = $name, rootNode=$rootNode)" +} diff --git a/trees/src/main/kotlin/bst/db/models/sql/Trees.kt b/trees/src/main/kotlin/bst/db/models/sql/Trees.kt new file mode 100644 index 0000000..571e320 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/models/sql/Trees.kt @@ -0,0 +1,14 @@ +package bst.db.models.sql + +import org.jetbrains.exposed.dao.id.IntIdTable + +/** + * Represents the database table for storing tree entities in the SQL database. + * + * @property name Column for the name of the tree. + * @property rootNode Column for the root node reference of the tree, allowing null values. + */ +object Trees : IntIdTable("trees") { + val name = varchar("name", length = 128).uniqueIndex() + val rootNode = reference("rootNode", Nodes.id).nullable() +} diff --git a/trees/src/main/kotlin/bst/db/serializeClasses/SerializableNode.kt b/trees/src/main/kotlin/bst/db/serializeClasses/SerializableNode.kt new file mode 100644 index 0000000..dd7bfde --- /dev/null +++ b/trees/src/main/kotlin/bst/db/serializeClasses/SerializableNode.kt @@ -0,0 +1,25 @@ +package bst.db.serializeClasses + +import kotlinx.serialization.Serializable + +/** + * Represents a serializable node in a binary search tree. + * + * @property key The key of the node. + * @property value The value associated with the node. + * @property x The x-coordinate of the node in a visualization, with a default value of 0.0. + * @property y The y-coordinate of the node in a visualization, with a default value of 0.0. + * @property metadata Additional metadata associated with the node, nullable. + * @property leftNode The left child node, nullable. + * @property rightNode The right child node, nullable. + */ +@Serializable +class SerializableNode( + val key: String, + val value: String, + var x: Double = 0.0, + var y: Double = 0.0, + var metadata: String? = null, + var leftNode: SerializableNode? = null, + var rightNode: SerializableNode? = null +) diff --git a/trees/src/main/kotlin/bst/db/serializeClasses/SerializableTree.kt b/trees/src/main/kotlin/bst/db/serializeClasses/SerializableTree.kt new file mode 100644 index 0000000..a4cbc33 --- /dev/null +++ b/trees/src/main/kotlin/bst/db/serializeClasses/SerializableTree.kt @@ -0,0 +1,15 @@ +package bst.db.serializeClasses + +import kotlinx.serialization.Serializable + +/** + * Represents a serializable tree in a binary search tree structure. + * + * @property treeName The name of the tree. + * @property rootNode The root node of the tree, nullable. + */ +@Serializable +class SerializableTree( + var treeName: String, + var rootNode: SerializableNode? +) diff --git a/trees/src/main/kotlin/bst/nodes/AVLNode.kt b/trees/src/main/kotlin/bst/nodes/AVLNode.kt new file mode 100644 index 0000000..be665d6 --- /dev/null +++ b/trees/src/main/kotlin/bst/nodes/AVLNode.kt @@ -0,0 +1,21 @@ +package bst.nodes + +/** + * Represents a node in an AVL Tree. + * + * @param K the type of the key. + * @param V the type of the value. + * @param key the key associated with this node. + * @param value the value associated with this node. + * @param BinaryNode the parent class representing a binary node. + */ + +class AVLNode, V>( + key: K, + value: V +) : BinaryNode>(key, value) { + /** + * Represents the height of the node. + */ + var height: Int = 0 +} diff --git a/trees/src/main/kotlin/bst/nodes/BSTNode.kt b/trees/src/main/kotlin/bst/nodes/BSTNode.kt new file mode 100644 index 0000000..ca1876e --- /dev/null +++ b/trees/src/main/kotlin/bst/nodes/BSTNode.kt @@ -0,0 +1,16 @@ +package bst.nodes + +/** + * Represents a node in a Binary Search Tree. + * + * @param K the type of the key. + * @param V the type of the value. + * @param key the key associated with this node. + * @param value the value associated with this node. + * @param BinaryNode the parent class representing a binary node. + */ + +class BSTNode, V>( + key: K, + value: V +) : BinaryNode>(key, value) diff --git a/trees/src/main/kotlin/bst/nodes/BinaryNode.kt b/trees/src/main/kotlin/bst/nodes/BinaryNode.kt new file mode 100644 index 0000000..60d2b95 --- /dev/null +++ b/trees/src/main/kotlin/bst/nodes/BinaryNode.kt @@ -0,0 +1,26 @@ +package bst.nodes + +/** + * Represents a binary node in a binary tree. + * + * @param K the type of the key. + * @param V the type of the value. + * @param Self the type of the node itself. + * @param key the key associated with this node. + * @param value the value associated with this node. + */ + +abstract class BinaryNode, V, Self : BinaryNode>( + var key: K, + var value: V +) { + /** + * Represents the left child node of this node. + */ + var left: Self? = null + + /** + * Represents the right child node of this node. + */ + var right: Self? = null +} diff --git a/trees/src/main/kotlin/bst/nodes/RBTNode.kt b/trees/src/main/kotlin/bst/nodes/RBTNode.kt new file mode 100644 index 0000000..77592a6 --- /dev/null +++ b/trees/src/main/kotlin/bst/nodes/RBTNode.kt @@ -0,0 +1,34 @@ +package bst.nodes + +/** + * Represents a node in a Red-Black Tree. + * + * @param K the type of the key. + * @param V the type of the value. + * @param key the key associated with this node. + * @param value the value associated with this node. + * @param color the color of the node. + * @param BinaryNode the parent class representing a binary node. + */ + +class RBTNode, V>( + key: K, + value: V, + var color: Color = Color.RED +) : BinaryNode>(key, value) { + + /** + * Returns the child node of this node based on the given flag. + * + * @param f a flag indicating whether to return the right child (true) or the left child (false). + * @return the child node of this node based on the given flag. + */ + internal fun child(f: Boolean) = if (f) right else left + + /** + * Represents the color of the node. + */ + enum class Color { + RED, BLACK + } +} diff --git a/trees/src/main/resources/simplelogger.properties b/trees/src/main/resources/simplelogger.properties new file mode 100644 index 0000000..8c3588c --- /dev/null +++ b/trees/src/main/resources/simplelogger.properties @@ -0,0 +1,3 @@ +org.slf4j.simpleLogger.defaultLogLevel=info +org.slf4j.simpleLogger.logFile=System.out +org.slf4j.simpleLogger.log.org.neo4j.ogm.drivers.bolt.request.BoltRequest=debug diff --git a/trees/src/test/kotlin/bst/AvlTest.kt b/trees/src/test/kotlin/bst/AvlTest.kt new file mode 100644 index 0000000..fba8807 --- /dev/null +++ b/trees/src/test/kotlin/bst/AvlTest.kt @@ -0,0 +1,175 @@ +package bst + +import bst.nodes.AVLNode +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Nested +import org.junit.jupiter.api.Test +import kotlin.math.max + +class AvlTest { + private fun , V> isAvl(node: AVLNode?): Boolean { + if (node == null) return true + return isAvl(node.left) && + isAvl(node.right) && + (subtreeHeight(node.left) - subtreeHeight(node.right) in -1..1) + } + + private fun , V> subtreeHeight(node: AVLNode?): Int { + if (node == null) return 0 + return max(subtreeHeight(node.left), subtreeHeight(node.right)) + 1 + } + + private fun , V> countNodes(node: AVLNode?): Int { + if (node == null) return 0 + return countNodes(node.left) + countNodes(node.right) + 1 + } + + private lateinit var tree: AVLTree + private val values = IntArray(1000) { it + 1 } + + @BeforeEach + fun initializeObjects() { + tree = AVLTree() + } + + @Test + fun `validate tree if empty`() { + assertNull(tree.rootNode) + assertEquals(0, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Nested + inner class InsertionTests { + @Test + fun `insert a few key-value pairs`() { + tree.insert(2, 2) + tree.insert(3, 3) + tree.insert(1, 1) + + assertEquals(2, tree.rootNode?.key) + assertEquals(3, tree.rootNode?.right?.key) + assertEquals(1, tree.rootNode?.left?.key) + + assertEquals(3, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `check left-left rotation case`() { + tree.insert(3, 3) + tree.insert(2, 2) + tree.insert(1, 1) + + assertEquals(2, tree.rootNode?.key) + assertEquals(1, tree.rootNode?.left?.key) + assertEquals(3, tree.rootNode?.right?.key) + + assertEquals(3, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `check left-right rotation case`() { + tree.insert(5, 5) + tree.insert(3, 3) + tree.insert(4, 4) + + assertEquals(4, tree.rootNode?.key) + assertEquals(3, tree.rootNode?.left?.key) + assertEquals(5, tree.rootNode?.right?.key) + + assertEquals(3, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `check right-right rotation case`() { + tree.insert(3, 3) + tree.insert(4, 4) + tree.insert(5, 5) + + assertEquals(4, tree.rootNode?.key) + assertEquals(3, tree.rootNode?.left?.key) + assertEquals(5, tree.rootNode?.right?.key) + + assertEquals(3, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `check right-left rotation case`() { + tree.insert(3, 3) + tree.insert(5, 5) + tree.insert(4, 4) + + assertEquals(4, tree.rootNode?.key) + assertEquals(3, tree.rootNode?.left?.key) + assertEquals(5, tree.rootNode?.right?.key) + + assertEquals(3, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `insert same key twice`() { + tree.insert(1, 1) + tree.insert(1, 2) + assertEquals(1, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `insert many key-value pairs`() { + values.forEach { tree.insert(it, it) } + assertEquals(1000, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + } + + @Nested + inner class FindTests { + @Test + fun `find a node by its key`() { + values.forEach { tree.insert(it, it) } + values.forEach { assertEquals(it, tree.find(it)) } + } + + @Test + fun `find by non-existing key`() { + values.forEach { tree.insert(it, it) } + assertNull(tree.find(-1)) + } + } + + @Nested + inner class DeletionTests { + @Test + fun `delete one key-value pair`() { + tree.insert(1, 1) + tree.remove(1) + assertEquals(0, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + + @Test + fun `delete non-existent key`() { + tree.insert(3, 3) + tree.insert(4, 4) + tree.insert(1, 1) + tree.remove(-1) + assertEquals(3, countNodes(tree.rootNode)) + } + + @Test + fun `delete many key-value pairs`() { + values.forEach { tree.insert(it, it) } + values.take(500).forEach { tree.remove(it) } + assertEquals(500, countNodes(tree.rootNode)) + assertTrue(isAvl(tree.rootNode)) + } + } +} diff --git a/trees/src/test/kotlin/bst/BstTest.kt b/trees/src/test/kotlin/bst/BstTest.kt new file mode 100644 index 0000000..63013d2 --- /dev/null +++ b/trees/src/test/kotlin/bst/BstTest.kt @@ -0,0 +1,59 @@ +package bst + +import bst.nodes.BSTNode +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class BstTest { + private fun , V> isBst(root: BSTNode?): Boolean { + if (root == null) { + return true + } + val left = root.left + val right = root.right + if ((left != null && left.key >= root.key) || (right != null && right.key <= root.key)) { + return false + } + return isBst(left) && isBst(right) + } + + private fun , V> countNodes(node: BSTNode?): Int { + if (node == null) return 0 + return countNodes(node.left) + countNodes(node.right) + 1 + } + + private lateinit var tree: BSTree + + @BeforeEach + fun initializeObjects() { + tree = BSTree() + } + + @Test + fun `validate tree if empty`() { + assertNull(tree.rootNode) + assertEquals(0, countNodes(tree.rootNode)) + assertTrue(isBst(tree.rootNode)) + } + + @Test + fun `verify invariants after each action`() { + val values = IntArray(1000) { it + 1 } + values.shuffle() + values.forEach { + tree.insert(it, it) + assertTrue(isBst(tree.rootNode)) + } + values.take(500).forEach { + tree.remove(it) + assertTrue(isBst(tree.rootNode)) + } + values.takeLast(500).forEach { + assertNotEquals(null, tree.find(it)) + } + } +} diff --git a/trees/src/test/kotlin/bst/RbtTest.kt b/trees/src/test/kotlin/bst/RbtTest.kt new file mode 100644 index 0000000..b960b81 --- /dev/null +++ b/trees/src/test/kotlin/bst/RbtTest.kt @@ -0,0 +1,164 @@ +package bst + +import bst.nodes.RBTNode +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Nested +import org.junit.jupiter.api.Test + +class RbtTest { + /* + This function makes sure that a tree is indeed red-black by walking over + every node and checking invariants. If it returns 0 that means + the tree is invalid red-black tree, and any other number is the black height + of the entire tree. + */ + private fun , V> isRbt(root: RBTNode?): Int { + if (root == null) { + return 1 + } + val left = root.left + val right = root.right + if (isRed(root)) { + if (isRed(left) && isRed(right)) { + return 0 + } + } + val leftHeight = isRbt(left) + val rightHeight = isRbt(right) + + // Invalid binary search tree + if ((left != null && left.key >= root.key) || (right != null && right.key <= root.key)) { + return 0 + } + + // Black height mismatch + if (leftHeight != 0 && rightHeight != 0 && leftHeight != rightHeight) { + return 0 + } + + // Counting black links + return if (leftHeight != 0 && rightHeight != 0) { + if (isRed(root)) leftHeight else leftHeight + 1 + } else { + 0 + } + } + + private fun , V> isRed(node: RBTNode?): Boolean { + return node != null && node.color == RBTNode.Color.RED + } + + private fun , V> countNodes(node: RBTNode?): Int { + if (node == null) return 0 + return countNodes(node.left) + countNodes(node.right) + 1 + } + + private lateinit var tree: RedBlackTree + private val values = IntArray(1_000_000) { it + 1 } + + @BeforeEach + fun initializeObjects() { + tree = RedBlackTree() + } + + @Test + fun `validate tree if empty`() { + assertNull(tree.rootNode) + assertEquals(0, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + + @Test + fun `verify invariants after each action`() { + values.take(1000).forEach { + tree.insert(it, it.toString()) + assertNotEquals(0, isRbt(tree.rootNode)) + } + values.take(500).forEach { + tree.remove(it) + assertNotEquals(0, isRbt(tree.rootNode)) + } + assertEquals(500, countNodes(tree.rootNode)) + } + + @Nested + inner class InsertionTests { + @Test + fun `insert single key-value pair`() { + tree.insert(1, "A") + assertEquals(1, tree.rootNode?.key) + assertEquals(1, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + + @Test + fun `insert a few key-value pairs`() { + tree.insert(19, "S") + tree.insert(5, "E") + tree.insert(1, "A") + tree.insert(18, "R") + assertEquals("E", tree.rootNode?.let { tree.find(it.key) }) + assertEquals("A", tree.rootNode?.left?.let { tree.find(it.key) }) + assertEquals(null, tree.find(10)) + + assertEquals(4, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + + @Test + fun `insert same key twice`() { + tree.insert(1, "A") + tree.insert(1, "B") + assertEquals(1, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + assertEquals("B", tree.find(1)) + } + } + + @Nested + inner class DeleteTests { + @Test + fun `delete one key-value pair`() { + tree.insert(2, "B") + tree.remove(2) + assertEquals(0, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + + @Test + fun `delete non-existent key-value pair`() { + tree.insert(2, "B") + tree.remove(3) + assertEquals(1, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + + @Test + fun `delete a few key-value pairs`() { + tree.insert(19, "S") + tree.insert(5, "E") + tree.insert(1, "A") + tree.insert(18, "R") + tree.remove(1) + tree.remove(19) + assertEquals("R", tree.find(18)) + assertEquals(null, tree.find(1)) + tree.remove(18) + assertEquals("E", tree.find(5)) + assertEquals(null, tree.find(18)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + + @Test + fun `delete many key-value pairs`() { + values.shuffle() + values.forEach { tree.insert(it, it.toString()) } + values.take(500_000).forEach { tree.remove(it) } + assertEquals(500_000, countNodes(tree.rootNode)) + assertNotEquals(0, isRbt(tree.rootNode)) + } + } +}