diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..149f4c4
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+*.bat eol=crlf
+
diff --git a/.github/mergeable.yml b/.github/mergeable.yml
new file mode 100644
index 0000000..0e0e7e2
--- /dev/null
+++ b/.github/mergeable.yml
@@ -0,0 +1,26 @@
+version: 2
+mergeable:
+ - when: 'pull_request.*, pull_request_review.*'
+ filter:
+ - do: payload
+ pull_request:
+ title:
+ must_exclude:
+ regex: ^Feedback$
+ regex_flag: none
+ validate:
+ - do: approvals
+ min:
+ count: 1
+ block:
+ changes_requested: true
+ limit:
+ users:
+ - ALanovaya
+ - PavlushaSource
+ - AlexShmak
+
+ - do: description
+ no_empty:
+ enabled: true
+ message: Description matter and should not be empty. Provide detail with **what** was changed, **why** it was changed, and **how** it was changed.
\ No newline at end of file
diff --git a/.github/workflows/buildAndTest.yml b/.github/workflows/buildAndTest.yml
new file mode 100644
index 0000000..d918ba2
--- /dev/null
+++ b/.github/workflows/buildAndTest.yml
@@ -0,0 +1,39 @@
+name: Test and build with Gradle
+
+on:
+ push:
+
+jobs:
+ build:
+ runs-on: ${{ matrix.os }}
+
+ strategy:
+ matrix:
+ os: [macos-latest, ubuntu-latest, windows-latest]
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up JDK 17
+ uses: actions/setup-java@v3
+ with:
+ java-version: '17'
+ distribution: zulu
+ - name: Test and build with Gradle
+ uses: gradle/gradle-build-action@v2
+ with:
+ arguments: build
+
+ - if: matrix.os == 'ubuntu-latest'
+ name: Grant execute permission for gradlew
+ run: chmod +x gradlew
+
+ - if: matrix.os == 'ubuntu-latest'
+ name: Run Test Coverage
+ run: ./gradlew jacocoTestReport
+
+ - if: matrix.os == 'ubuntu-latest'
+ name: Jacoco Code Coverage Report
+ uses: cicirello/jacoco-badge-generator@v2.8.0
+ with:
+ generate-branches-badge: true
+ jacoco-csv-file: build/jacoco/report.csv
\ No newline at end of file
diff --git a/.github/workflows/publish-binaries.yaml b/.github/workflows/publish-binaries.yaml
new file mode 100644
index 0000000..c1c67d8
--- /dev/null
+++ b/.github/workflows/publish-binaries.yaml
@@ -0,0 +1,59 @@
+name: Publish binaries
+
+on:
+ push:
+ tags:
+ - v1.*
+ - v1.*.*
+
+permissions:
+ contents: write
+
+# Required to make env var work on Windows
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ build:
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+
+ runs-on: ${{ matrix.os }}
+
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v3
+ with:
+ distribution: 'temurin'
+ java-version: '17'
+ #cache: 'gradle'
+
+ - name: Build with Gradle
+ run: ./gradlew jpackageZip
+
+ - run: echo "OR_TARGET_NAME=linux-x64" >> $GITHUB_ENV
+ if: matrix.os == 'ubuntu-latest'
+
+ - run: echo "OR_TARGET_NAME=macos" >> $GITHUB_ENV
+ if: matrix.os == 'macos-latest'
+
+ - run: echo "OR_TARGET_NAME=windows" >> $GITHUB_ENV
+ if: matrix.os == 'windows-latest'
+
+ - name: Rename jpackage zip
+ run: mv ./build/distributions/openrndr-application.zip ./build/distributions/openrndr-application-${{env.OR_TARGET_NAME}}.zip
+
+ - name: Create Release
+ uses: ncipollo/release-action@v1.12.0
+ id: create_release
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ allowUpdates: true
+ replacesArtifacts: false
+ body: Fully automated release
+ artifacts: "./build/distributions/openrndr-application-${{env.OR_TARGET_NAME}}.zip"
+
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..974da82
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+application.log
+build
+out
+.idea
+.gradle
+video/
+screenshots/
+gui-parameters/
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..81fbe60
--- /dev/null
+++ b/LICENSE.md
@@ -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
+.
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..860433e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,71 @@
+# trees-5
+
+---
+
+> `trees-5` - This is an application that allows you to visualize the work of such types of binary trees as
+> [Simple Binary Search Trees](https://en.wikipedia.org/wiki/Binary_search_tree), [AVL Trees](https://en.wikipedia.org/wiki/AVL_trees),
+> [Red-Black Trees](https://en.wikipedia.org/wiki/Red–black_tree).
+
+### The application supports saving trees to databases
+- Simple Binary Search Trees in **Json** flat file
+- AVL Trees in **SQLite**
+- Red-Black Trees in **Neo4j**
+
+---
+
+
+## Getting started
+
+
+### Build
+
+To build and run this application locally, you'll need Git, Gradle and JDK installed on your computer. From your command
+line:
+
+```bash
+# Clone this repository
+git clone https://github.com/spbu-coding-2022/trees-5.git
+
+# Go into the repository
+cd trees-5
+
+# Build
+./gradlew assemble
+# Or use `./gradlew build` if you want to test and lint app
+
+# Run the app
+./gradlew run
+```
+
+### Neo4j database
+>This database requires a separate connection to store in it Red-Black Trees
+
+TO-DO __A brief guide__ \
+If you got trouble during installation or for more information visit [site](https://neo4j.com/docs/operations-manual/current/installation/)
+
+---
+
+## More information about the app
+
+### How to get started with tree
+
+First, select the type of binary tree you will work with, then start entering values of keys to insert into the tree. If you want to insert a key and a value, then you need to type the value of the key in the input line first, then use the separator in the form ';' and write the value to be stored with the key.
+
+### Working with a binary tree
+
+You can work on all third types of binary trees at the s~~~~ame time.
+What type the tree will have is determined by the first entered value, if it is a string value, then the comparison will be defined for strings, otherwise the tree will be numeric and after string keys simply will not be inserted into it.
+To show the value of the nodes, press the left shift, pressing again, the keys will show again.
+To delete or find a node with a specific key, you must enter the key and click the remove or find button.
+If you want to hide the tree, then this can be done by pressing the space bar.
+
+## Screenshots
+
+
+
+~~~~
+---
+
+### License
+
+Distributed under the GNU GPL v3.0 License. See [LICENSE](LICENSE) for more information.
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..375848d
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,356 @@
+import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
+import org.gradle.internal.os.OperatingSystem
+import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
+
+group = "trees"
+version = "1.0.0"
+
+val applicationMainClass = "MainKt"
+
+/** ## additional ORX features to be added to this project */
+val orxFeatures = setOf(
+// "orx-boofcv",
+ "orx-camera",
+// "orx-chataigne",
+ "orx-color",
+ "orx-compositor",
+// "orx-dnk3",
+// "orx-easing",
+// "orx-file-watcher",
+ "orx-fx",
+// "orx-glslify",
+// "orx-gradient-descent",
+// "orx-git-archiver",
+ "orx-gui",
+ "orx-image-fit",
+// "orx-integral-image",
+// "orx-interval-tree",
+// "orx-jumpflood",
+// "orx-kdtree",
+// "orx-keyframer",
+// "orx-kinect-v1",
+// "orx-kotlin-parser",
+// "orx-mesh-generators",
+// "orx-midi",
+// "orx-minim",
+ "orx-no-clear",
+ "orx-noise",
+// "orx-obj-loader",
+ "orx-olive",
+// "orx-osc",
+// "orx-palette",
+ "orx-panel",
+// "orx-parameters",
+// "orx-poisson-fill",
+// "orx-rabbit-control",
+// "orx-realsense2",
+// "orx-runway",
+ "orx-shade-styles",
+// "orx-shader-phrases",
+ "orx-shapes",
+// "orx-syphon",
+// "orx-temporal-blur",
+// "orx-tensorflow",
+// "orx-time-operators",
+// "orx-timer",
+// "orx-triangulation",
+ "orx-video-profiles",
+ "orx-view-box",
+)
+
+/** ## additional ORML features to be added to this project */
+val ormlFeatures = setOf(
+// "orml-blazepose",
+// "orml-dbface",
+// "orml-facemesh",
+// "orml-image-classifier",
+// "orml-psenet",
+// "orml-ssd",
+// "orml-style-transfer",
+// "orml-super-resolution",
+// "orml-u2net",
+)
+
+/** ## additional OPENRNDR features to be added to this project */
+val openrndrFeatures = setOfNotNull(
+ if (DefaultNativePlatform("current").architecture.name != "arm-v8") "video" else null
+)
+
+/** ## configure the type of logging this project uses */
+enum class Logging { NONE, SIMPLE, FULL }
+
+val applicationLogging = Logging.FULL
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+@Suppress("DSL_SCOPE_VIOLATION")
+plugins {
+ java
+ alias(libs.plugins.kotlin.jvm)
+ alias(libs.plugins.shadow)
+ alias(libs.plugins.runtime)
+ alias(libs.plugins.gitarchive.tomarkdown).apply(false)
+ jacoco
+}
+
+repositories {
+ mavenCentral()
+ mavenLocal()
+}
+
+dependencies {
+ implementation(libs.jackson.kotlin)
+
+ implementation(libs.exposed.core)
+ implementation(libs.exposed.dao)
+ implementation(libs.exposed.jdbc)
+ implementation(libs.sqlite)
+
+ implementation(libs.neo4j.driver)
+
+ testImplementation(libs.junit.jupiter)
+
+ implementation(libs.kotlinx.coroutines.core)
+ implementation(libs.slf4j.api)
+ implementation(libs.kotlin.logging)
+
+ when (applicationLogging) {
+ Logging.NONE -> {
+ runtimeOnly(libs.slf4j.nop)
+ }
+
+ Logging.SIMPLE -> {
+ runtimeOnly(libs.slf4j.simple)
+ }
+
+ Logging.FULL -> {
+ runtimeOnly(libs.log4j.slf4j2)
+ runtimeOnly(libs.log4j.core)
+ }
+ }
+}
+
+tasks.test {
+ useJUnitPlatform()
+}
+
+tasks.test {
+ finalizedBy(tasks.jacocoTestReport)
+}
+
+tasks.jacocoTestReport {
+ dependsOn(tasks.test)
+ reports {
+ xml.required.set(true)
+ xml.outputLocation.set(layout.buildDirectory.file("jacoco/report.xml"))
+ csv.required.set(true)
+ csv.outputLocation.set(layout.buildDirectory.file("jacoco/report.csv"))
+ html.required.set(true)
+ html.outputLocation.set(layout.buildDirectory.dir("jacocoHtml"))
+ }
+}
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+java {
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
+}
+tasks.withType {
+ kotlinOptions.jvmTarget = "11"
+}
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+project.setProperty("mainClassName", applicationMainClass)
+
+application {
+ if (hasProperty("openrndr.application")) {
+ mainClass.set("${property("openrndr.application")}")
+ }
+}
+
+tasks {
+ named("shadowJar") {
+ manifest {
+ attributes["Main-Class"] = applicationMainClass
+ attributes["Implementation-Version"] = project.version
+ }
+ minimize {
+ exclude(dependency("org.openrndr:openrndr-gl3:.*"))
+ exclude(dependency("org.jetbrains.kotlin:kotlin-reflect:.*"))
+ exclude(dependency("org.slf4j:slf4j-simple:.*"))
+ exclude(dependency("org.apache.logging.log4j:log4j-slf4j2-impl:.*"))
+ exclude(dependency("com.fasterxml.jackson.core:jackson-databind:.*"))
+ exclude(dependency("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:.*"))
+ }
+ }
+ named("jpackage") {
+ doLast {
+ when (OperatingSystem.current()) {
+ OperatingSystem.WINDOWS, OperatingSystem.LINUX -> {
+ copy {
+ from("data") {
+ include("**/*")
+ }
+ into("build/jpackage/openrndr-application/data")
+ }
+ }
+
+ OperatingSystem.MAC_OS -> {
+ copy {
+ from("data") {
+ include("**/*")
+ }
+ into("build/jpackage/openrndr-application.app/Contents/Resources/data")
+ }
+ }
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+tasks.register("jpackageZip") {
+ archiveFileName.set("openrndr-application.zip")
+ from("$buildDir/jpackage") {
+ include("**/*")
+ }
+}
+tasks.findByName("jpackageZip")?.dependsOn("jpackage")
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+runtime {
+ jpackage {
+ imageName = "openrndr-application"
+ skipInstaller = true
+ if (OperatingSystem.current() == OperatingSystem.MAC_OS) {
+ jvmArgs.add("-XstartOnFirstThread")
+ jvmArgs.add("-Duser.dir=${"$"}APPDIR/../Resources")
+ }
+ }
+ options.set(listOf("--strip-debug", "--compress", "1", "--no-header-files", "--no-man-pages"))
+ modules.set(listOf("jdk.unsupported", "java.management", "java.desktop"))
+}
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+tasks.register("gitArchiveToMarkDown") {
+ historySize.set(20)
+}
+
+// ------------------------------------------------------------------------------------------------------------------ //
+
+class Openrndr {
+ val openrndrVersion = libs.versions.openrndr.get()
+ val orxVersion = libs.versions.orx.get()
+ val ormlVersion = libs.versions.orml.get()
+
+ // choices are "orx-tensorflow-gpu", "orx-tensorflow"
+ val orxTensorflowBackend = "orx-tensorflow"
+
+ val os = if (project.hasProperty("targetPlatform")) {
+ val supportedPlatforms = setOf("windows", "macos", "linux-x64", "linux-arm64")
+ val platform: String = project.property("targetPlatform") as String
+ if (platform !in supportedPlatforms) {
+ throw IllegalArgumentException("target platform not supported: $platform")
+ } else {
+ platform
+ }
+ } else when (OperatingSystem.current()) {
+ OperatingSystem.WINDOWS -> "windows"
+ OperatingSystem.MAC_OS -> when (val h = DefaultNativePlatform("current").architecture.name) {
+ "aarch64", "arm-v8" -> "macos-arm64"
+ else -> "macos"
+ }
+
+ OperatingSystem.LINUX -> when (val h = DefaultNativePlatform("current").architecture.name) {
+ "x86-64" -> "linux-x64"
+ "aarch64" -> "linux-arm64"
+ else -> throw IllegalArgumentException("architecture not supported: $h")
+ }
+
+ else -> throw IllegalArgumentException("os not supported")
+ }
+
+ fun orx(module: String) = "org.openrndr.extra:$module:$orxVersion"
+ fun orml(module: String) = "org.openrndr.orml:$module:$ormlVersion"
+ fun openrndr(module: String) = "org.openrndr:openrndr-$module:$openrndrVersion"
+ fun openrndrNatives(module: String) = "org.openrndr:openrndr-$module-natives-$os:$openrndrVersion"
+ fun orxNatives(module: String) = "org.openrndr.extra:$module-natives-$os:$orxVersion"
+
+ init {
+ dependencies {
+ runtimeOnly(openrndr("gl3"))
+ runtimeOnly(openrndrNatives("gl3"))
+ implementation(openrndr("openal"))
+ runtimeOnly(openrndrNatives("openal"))
+ implementation(openrndr("application"))
+ implementation(openrndr("svg"))
+ implementation(openrndr("animatable"))
+ implementation(openrndr("extensions"))
+ implementation(openrndr("filter"))
+ implementation(openrndr("dialogs"))
+ if ("video" in openrndrFeatures) {
+ implementation(openrndr("ffmpeg"))
+ runtimeOnly(openrndrNatives("ffmpeg"))
+ }
+ for (feature in orxFeatures) {
+ implementation(orx(feature))
+ }
+ for (feature in ormlFeatures) {
+ implementation(orml(feature))
+ }
+ if ("orx-tensorflow" in orxFeatures) runtimeOnly("org.openrndr.extra:$orxTensorflowBackend-natives-$os:$orxVersion")
+ if ("orx-kinect-v1" in orxFeatures) runtimeOnly(orxNatives("orx-kinect-v1"))
+ if ("orx-olive" in orxFeatures) implementation(libs.kotlin.script.runtime)
+ }
+ }
+}
+
+val openrndr = Openrndr()
+
+if (properties["openrndr.tasks"] == "true") {
+ task("create executable jar for $applicationMainClass") {
+ group = " \uD83E\uDD8C OPENRNDR"
+ dependsOn("shadowJar")
+ }
+
+ task("run $applicationMainClass") {
+ group = " \uD83E\uDD8C OPENRNDR"
+ dependsOn("run")
+ }
+
+ task("create standalone executable for $applicationMainClass") {
+ group = " \uD83E\uDD8C OPENRNDR"
+ dependsOn("jpackageZip")
+ }
+
+ task("add IDE file scopes") {
+ group = " \uD83E\uDD8C OPENRNDR"
+ val scopesFolder = File("${project.projectDir}/.idea/scopes")
+ scopesFolder.mkdirs()
+
+ val files = listOf(
+ "Code" to "file:*.kt||file:*.frag||file:*.vert||file:*.glsl",
+ "Text" to "file:*.txt||file:*.md||file:*.xml||file:*.json",
+ "Gradle" to "file[*buildSrc*]:*/||file:*gradle.*||file:*.gradle||file:*/gradle-wrapper.properties||file:*.toml",
+ "Images" to "file:*.png||file:*.jpg||file:*.dds||file:*.exr"
+ )
+ files.forEach { (name, pattern) ->
+ val file = File(scopesFolder, "__$name.xml")
+ if (!file.exists()) {
+ file.writeText(
+ """
+
+
+
+ """.trimIndent()
+ )
+ }
+ }
+ }
+}
diff --git a/data/fonts/default.otf b/data/fonts/default.otf
new file mode 100644
index 0000000..8e72e14
Binary files /dev/null and b/data/fonts/default.otf differ
diff --git a/data/fonts/license.txt b/data/fonts/license.txt
new file mode 100644
index 0000000..f72f765
--- /dev/null
+++ b/data/fonts/license.txt
@@ -0,0 +1,92 @@
+Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
\ No newline at end of file
diff --git a/data/images/cheeta.jpg b/data/images/cheeta.jpg
new file mode 100644
index 0000000..0bcc9b7
Binary files /dev/null and b/data/images/cheeta.jpg differ
diff --git a/data/images/pm5544.png b/data/images/pm5544.png
new file mode 100644
index 0000000..4c55c9d
Binary files /dev/null and b/data/images/pm5544.png differ
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..fbb0c0b
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,4 @@
+openrndr.tasks=true
+kotlin.code.style=official
+org.gradle.unsafe.configuration-cache=false
+
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
new file mode 100644
index 0000000..60ebec4
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,40 @@
+[versions]
+kotlin = "1.8.21"
+openrndr = "0.4.2"
+orx = "0.4.2"
+orml = "0.4.1"
+
+exposed = "0.38.1"
+
+slf4j = "2.0.7"
+log4j = "2.20.0"
+
+
+[libraries]
+kotlin-script-runtime = { group = "org.jetbrains.kotlin", name = "kotlin-script-runtime", version.ref = "kotlin" }
+
+slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
+slf4j-nop = { group = "org.slf4j", name = "slf4j-nop", version.ref = "slf4j" }
+slf4j-simple = { group = "org.slf4j", name = "slf4j-simple", version.ref = "slf4j" }
+log4j-slf4j2 = { group = "org.apache.logging.log4j", name = "log4j-slf4j2-impl", version.ref = "log4j" }
+log4j-core = { group = "org.apache.logging.log4j", name = "log4j-core", version.ref = "log4j" }
+
+jackson-kotlin = { group = "com.fasterxml.jackson.module", name = "jackson-module-kotlin", version = "2.14.2" }
+
+exposed-core = { group = "org.jetbrains.exposed", name = "exposed-core", version.ref = "exposed" }
+exposed-dao = { group = "org.jetbrains.exposed", name = "exposed-dao", version.ref = "exposed" }
+exposed-jdbc = { group = "org.jetbrains.exposed", name = "exposed-jdbc", version.ref = "exposed" }
+sqlite = { group = "org.xerial", name = "sqlite-jdbc", version = "3.41.2.1" }
+
+neo4j-driver = { group = "org.neo4j.driver", name = "neo4j-java-driver", version = "5.7.0" }
+
+kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version = "1.6.4" }
+kotlin-logging = { group = "io.github.microutils", name = "kotlin-logging", version = "3.0.5" }
+junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version = "5.9.2" }
+
+
+[plugins]
+kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
+shadow = { id = "com.github.johnrengelman.shadow", version = "7.1.2" }
+runtime = { id = "org.beryx.runtime", version = "1.13.0" }
+gitarchive-tomarkdown = { id = "org.openrndr.extra.gitarchiver.tomarkdown", version.ref = "orx" }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..c1962a7
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..37aef8d
--- /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.1.1-bin.zip
+networkTimeout=10000
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..aeb74cb
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,245 @@
+#!/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
+
+# 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
+
+
+# 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"'
+
+# 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/settings.gradle.kts b/settings.gradle.kts
new file mode 100644
index 0000000..9f9abf4
--- /dev/null
+++ b/settings.gradle.kts
@@ -0,0 +1,8 @@
+rootProject.name = "trees-5"
+
+pluginManagement {
+ repositories {
+ gradlePluginPortal()
+ mavenLocal()
+ }
+}
diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt
new file mode 100644
index 0000000..7dcd1fd
--- /dev/null
+++ b/src/main/kotlin/Main.kt
@@ -0,0 +1,625 @@
+import org.openrndr.*
+import org.openrndr.color.ColorRGBa
+import org.openrndr.draw.LineCap
+import org.openrndr.draw.loadFont
+import org.openrndr.panel.ControlManager
+import org.openrndr.panel.layout
+import kotlin.math.pow
+import org.openrndr.panel.elements.*
+import trees.*
+import trees.avltree.AVLTree
+import trees.bstree.BinarySearchTree
+import trees.rbtree.RedBlackTree
+
+fun main() = application {
+ configure {
+ width = 1280
+ height = 720
+ windowResizable = true
+ title = "Trees Renderer"
+ }
+
+ var input = ""
+ program {
+ // States of drawing trees
+ var stateDrawingBST = true
+ var stateDrawingAVL = false
+ var stateDrawingRBT = false
+
+ // Radius of drawing nodes
+ val radius = width / 90.0 + height / 50.0
+ // State of drawing value of node
+ var stateDrawingValue = false
+
+ // Flags of first input of nodes
+ var firstInputBST = true
+ var firstInputAVL = true
+ var firstInputRBT = true
+ // Value of key to find in tree
+ var keyStringFinding: String? = null
+ var keyIntFinding: Int? = null
+
+ // Trees to type matching of key
+ val BSTString = BinarySearchTree()
+ val BSTInt = BinarySearchTree()
+
+ val RBTString = RedBlackTree()
+ val RBTInt = RedBlackTree()
+
+ val AVLString = AVLTree()
+ val AVLInt = AVLTree()
+
+ // Flag of using type of tree (if false we use string key bst else int key bst)
+ var stringOrIntBSTFlag = false
+ var stringOrIntAVLFlag = false
+ var stringOrIntRBTFlag = false
+
+ keyboard.character.listen {
+ input += it.character
+ }
+
+ fun insertNode(input: String) {
+ val str = input.split(";")
+ val key: String?
+ val value: String?
+ if (str.size > 1) {
+ key = str[0]
+ value = str[1]
+ } else {
+ key = input
+ value = ""
+ }
+ if (stateDrawingBST) {
+ if (firstInputBST) {
+ firstInputBST = false
+ if (input.toIntOrNull() != null)
+ stringOrIntBSTFlag = true
+ }
+ if (input.isNotEmpty()) {
+ if (stringOrIntBSTFlag) {
+ if (input.toIntOrNull() != null)
+ BSTInt.insert(key.toInt(), value)
+ } else
+ BSTString.insert(key, value)
+ }
+ } else if (stateDrawingAVL) {
+ if (firstInputAVL) {
+ firstInputAVL = false
+ if (input.toIntOrNull() != null)
+ stringOrIntAVLFlag = true
+ }
+ if (input.isNotEmpty()) {
+ if (stringOrIntAVLFlag) {
+ if (input.toIntOrNull() != null)
+ AVLInt.insert(key.toInt(), value)
+ } else
+ AVLString.insert(key, value)
+ }
+ } else {
+ if (firstInputRBT) {
+ firstInputRBT = false
+ if (input.toIntOrNull() != null)
+ stringOrIntRBTFlag = true
+ }
+ if (input.isNotEmpty()) {
+ if (stringOrIntRBTFlag) {
+ if (input.toIntOrNull() != null)
+ RBTInt.insert(key.toInt(), value)
+ } else
+ RBTString.insert(key, value)
+ }
+ }
+ }
+
+ fun removeNode(input: String) {
+ if (stateDrawingBST) {
+ if (stringOrIntBSTFlag)
+ BSTInt.remove(input.toInt())
+ else
+ BSTString.remove(input)
+ } else if (stateDrawingAVL) {
+ if (stringOrIntAVLFlag)
+ AVLInt.remove(input.toInt())
+ else
+ AVLString.remove(input)
+ } else {
+ if (stringOrIntRBTFlag)
+ RBTInt.remove(input.toInt())
+ else
+ RBTString.remove(input)
+ }
+ }
+
+ fun findNode(input: String) {
+ if (stateDrawingBST) {
+ if (stringOrIntBSTFlag)
+ keyIntFinding = input.toInt()
+ else
+ keyStringFinding = input
+ } else if (stateDrawingAVL) {
+ if (stringOrIntAVLFlag)
+ keyIntFinding = input.toInt()
+ else
+ keyStringFinding = input
+ } else {
+ if (stringOrIntRBTFlag)
+ keyIntFinding = input.toInt()
+ else
+ keyStringFinding = input
+ }
+ }
+
+ keyboard.keyDown.listen {
+ if (it.key == KEY_ENTER) {
+ insertNode(input)
+ input = ""
+ }
+ if (it.key == KEY_BACKSPACE) {
+ if (input.isNotEmpty()) {
+ input = input.substring(0, input.length - 1)
+ }
+ }
+ }
+
+ extend(ControlManager()) {
+ layout {
+ button {
+ label = "Binary Search Tree"
+ clicked {
+ stateDrawingBST = stateDrawingBST xor true
+ if (stateDrawingBST) {
+ stateDrawingAVL = false
+ stateDrawingRBT = false
+ }
+ }
+ }
+ button {
+ label = " AVL Tree "
+ clicked {
+ stateDrawingAVL = stateDrawingAVL xor true
+ if (stateDrawingAVL) {
+ stateDrawingBST = false
+ stateDrawingRBT = false
+ }
+ }
+ }
+ button {
+ label = " Red Black Tree "
+ clicked {
+ stateDrawingRBT = stateDrawingRBT xor true
+ if (stateDrawingRBT) {
+ stateDrawingBST = false
+ stateDrawingAVL = false
+ }
+ }
+ }
+ button {
+ label = " Insert Node "
+ clicked {
+ insertNode(input)
+ input = ""
+ }
+ }
+ button {
+ label = " Remove Node "
+ clicked {
+ if (input.isNotEmpty())
+ removeNode(input)
+ input = ""
+ }
+ }
+ button {
+ label = " Find Node "
+ clicked {
+ findNode(input)
+ input = ""
+ }
+ }
+ }
+ }
+ val font = loadFont("data/fonts/default.otf", width / 100.0 + height / 100.0)
+ fun textDrawer(text: String, x: Double, y: Double, color: ColorRGBa = ColorRGBa.BLACK) {
+ drawer.fontMap = font
+ drawer.fill = color
+ drawer.text(text, x, y)
+ }
+
+ fun nodeDrawer(x: Double, y: Double, radius: Double, color: ColorRGBa = ColorRGBa.WHITE) {
+ drawer.fill = color
+ drawer.stroke = null
+ drawer.strokeWeight = 1.0
+ drawer.circle(x, y, radius)
+ }
+
+ fun lineDrawer(x1: Double, y1: Double, x2: Double, y2: Double) {
+ drawer.stroke = ColorRGBa.BLACK
+ drawer.strokeWeight = 1.0
+ drawer.lineCap = LineCap.SQUARE
+ drawer.lineSegment(x1, y1, x2, y2)
+ }
+
+ fun squareDraw(x: Double, y: Double, w: Double) {
+ drawer.fill = ColorRGBa.GRAY
+ drawer.stroke = null
+ drawer.strokeWeight = 1.0
+ drawer.rectangle(x, y, w, w)
+ }
+ keyboard.keyDown.listen {
+ if (it.key == KEY_LEFT_SHIFT)
+ stateDrawingValue = stateDrawingValue xor true
+ }
+ fun > drawBinarySearchTree(
+ treeList: MutableList?>,
+ state: Boolean,
+ keyToFind: K? = null
+ ) {
+ if (state == false || treeList[0]?.key == null)
+ return
+ val numberOfLevels = height(treeList[0])
+ drawer.clear(ColorRGBa.PINK)
+ var nodeIndex = 1
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ if (level == 1)
+ continue
+ var t = 0
+ var cnt = 0
+ for (k in 0 until power / 2 step 2) {
+ for (j in t until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ cnt++
+ if (cnt == 2) {
+ t = j + 2
+ cnt = 0
+ break
+ }
+ continue
+ }
+ lineDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ (width / (power / 2) + k * width / (power / 2)).toDouble(),
+ (level - 1) * height / (numberOfLevels + 1).toDouble()
+ )
+ cnt++
+ nodeIndex++
+ if (cnt == 2) {
+ t = j + 2
+ cnt = 0
+ break
+ }
+ }
+ }
+ }
+ nodeIndex = 0
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ for (j in 0 until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ continue
+ }
+ if (treeList[nodeIndex]?.key == keyToFind) {
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius,
+ ColorRGBa.BLUE
+ )
+ } else
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius
+ )
+ nodeIndex++
+ }
+ }
+ writer {
+ nodeIndex = 0
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ for (j in 0 until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ continue
+ }
+ val text = treeList[nodeIndex]?.key.toString()
+ val value = treeList[nodeIndex]?.value.toString()
+ nodeIndex++
+ val widthText = font.let {
+ drawer.fontMap = font
+ textWidth(text)
+ }
+ val widthValueText = font.let {
+ drawer.fontMap = font
+ textWidth(value)
+ }
+ val x = (width / power + j * width / power).toDouble()
+ val y = level * height / (numberOfLevels + 1).toDouble()
+ if (stateDrawingValue)
+ textDrawer(
+ value,
+ x - widthValueText / 2,
+ y + font.height / 2.0
+ )
+ else
+ textDrawer(
+ text,
+ x - widthText / 2,
+ y + font.height / 2.0
+ )
+ }
+ }
+ }
+ }
+
+ fun > drawRedBlackTree(
+ treeList: MutableList?>,
+ state: Boolean,
+ keyToFind: K? = null
+ ) {
+ if (state == false || treeList[0]?.key == null)
+ return
+ val numberOfLevels = height(treeList[0])
+ drawer.clear(ColorRGBa.PINK)
+ var nodeIndex = 1
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ if (level == 1)
+ continue
+ var t = 0
+ var cnt = 0
+ for (k in 0 until power / 2 step 2) {
+ for (j in t until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ cnt++
+ if (cnt == 2) {
+ t = j + 2
+ cnt = 0
+ break
+ }
+ continue
+ }
+ lineDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ (width / (power / 2) + k * width / (power / 2)).toDouble(),
+ (level - 1) * height / (numberOfLevels + 1).toDouble()
+ )
+ cnt++
+ nodeIndex++
+ if (cnt == 2) {
+ t = j + 2
+ cnt = 0
+ break
+ }
+ }
+ }
+ }
+ nodeIndex = 0
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ for (j in 0 until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ continue
+ }
+ if (treeList[nodeIndex]?.key == keyToFind) {
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius,
+ ColorRGBa.BLUE
+ )
+ } else if (treeList[nodeIndex]?.color == RedBlackTree.Color.BLACK)
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius,
+ ColorRGBa.BLACK
+ )
+ else
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius,
+ ColorRGBa.RED
+ )
+ nodeIndex++
+ }
+ }
+ writer {
+ nodeIndex = 0
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ for (j in 0 until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ continue
+ }
+ val text = treeList[nodeIndex]?.key.toString()
+ val value = treeList[nodeIndex]?.value.toString()
+ nodeIndex++
+ val widthText = font.let {
+ drawer.fontMap = font
+ textWidth(text)
+ }
+ val widthValueText = font.let {
+ drawer.fontMap = font
+ textWidth(value)
+ }
+ val x = (width / power + j * width / power).toDouble()
+ val y = level * height / (numberOfLevels + 1).toDouble()
+ if (stateDrawingValue)
+ textDrawer(
+ value,
+ x - widthValueText / 2,
+ y + font.height / 2.0,
+ ColorRGBa.WHITE
+ )
+ else
+ textDrawer(
+ text,
+ x - widthText / 2,
+ y + font.height / 2.0,
+ ColorRGBa.WHITE
+ )
+ }
+ }
+ }
+ }
+
+ fun > drawAVLtree(
+ treeList: MutableList?>,
+ state: Boolean,
+ keyToFind: K? = null
+ ) {
+ if (state == false || treeList[0]?.key == null)
+ return
+ val numberOfLevels = height(treeList[0])
+ drawer.clear(ColorRGBa.PINK)
+ var nodeIndex = 1
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ if (level == 1)
+ continue
+ var t = 0
+ var cnt = 0
+ for (k in 0 until power / 2 step 2) {
+ for (j in t until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ cnt++
+ if (cnt == 2) {
+ t = j + 2
+ cnt = 0
+ break
+ }
+ continue
+ }
+ lineDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ (width / (power / 2) + k * width / (power / 2)).toDouble(),
+ (level - 1) * height / (numberOfLevels + 1).toDouble()
+ )
+ cnt++
+ nodeIndex++
+ if (cnt == 2) {
+ t = j + 2
+ cnt = 0
+ break
+ }
+ }
+ }
+ }
+ nodeIndex = 0
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ for (j in 0 until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ continue
+ }
+ if (treeList[nodeIndex]?.key == keyToFind) {
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius,
+ ColorRGBa.BLUE
+ )
+ } else
+ nodeDrawer(
+ (width / power + j * width / power).toDouble(),
+ level * height / (numberOfLevels + 1).toDouble(),
+ radius
+ )
+ nodeIndex++
+ squareDraw(
+ (width / power + j * width / power).toDouble() - font.height,
+ level * height / (numberOfLevels + 1).toDouble() - font.height * 3.5,
+ font.height * 2
+ )
+ }
+ }
+ writer {
+ nodeIndex = 0
+ for (level in 1..numberOfLevels) {
+ val power = 2.0.pow(level).toInt()
+ for (j in 0 until power step 2) {
+ if (treeList[nodeIndex] == null) {
+ nodeIndex++
+ continue
+ }
+ val text = treeList[nodeIndex]?.key.toString()
+ val heightText = treeList[nodeIndex]?.height.toString()
+ val value = treeList[nodeIndex]?.value.toString()
+ val widthText = font.let {
+ drawer.fontMap = font
+ textWidth(text)
+ }
+ val widthHeightText = font.let {
+ drawer.fontMap = font
+ textWidth(heightText)
+ }
+ val widthValueText = font.let {
+ drawer.fontMap = font
+ textWidth(value)
+ }
+ val x = (width / power + j * width / power).toDouble()
+ val y = level * height / (numberOfLevels + 1).toDouble()
+ if (stateDrawingValue)
+ textDrawer(
+ value,
+ x - widthValueText / 2,
+ y + font.height / 2.0
+ )
+ else
+ textDrawer(
+ text,
+ x - widthText / 2,
+ y + font.height / 2.0
+ )
+ textDrawer(
+ heightText,
+ (width / power + j * width / power).toDouble() - widthHeightText / 2,
+ level * height / (numberOfLevels + 1).toDouble() - font.height * 2,
+ ColorRGBa.WHITE
+ )
+ nodeIndex++
+ }
+ }
+ }
+ }
+
+ extend {
+ drawer.clear(ColorRGBa.PINK)
+ if (stringOrIntBSTFlag)
+ drawBinarySearchTree(treeLevelOrder(BSTInt), stateDrawingBST, keyIntFinding)
+ else
+ drawBinarySearchTree(treeLevelOrder(BSTString), stateDrawingBST, keyStringFinding)
+ if (stringOrIntRBTFlag)
+ drawRedBlackTree(treeLevelOrder(RBTInt.root), stateDrawingRBT, keyIntFinding)
+ else
+ drawRedBlackTree(treeLevelOrder(RBTString.root), stateDrawingRBT, keyStringFinding)
+ if (stringOrIntAVLFlag)
+ drawAVLtree(treeLevelOrder(AVLInt), stateDrawingAVL, keyIntFinding)
+ else
+ drawAVLtree(treeLevelOrder(AVLString), stateDrawingAVL, keyStringFinding)
+ writer {
+ val widthText = font.let {
+ drawer.fontMap = font
+ textWidth(input)
+ }
+ drawer.fill = ColorRGBa.WHITE
+ drawer.stroke = null
+ drawer.strokeWeight = 1.0
+ drawer.rectangle(0.0, height - font.height * 3.0, widthText + font.height * 2, font.height * 3.0)
+ textDrawer(input, 0 + font.height, height - font.height)
+ }
+ }
+ }
+}
diff --git a/src/main/kotlin/database/json/bstJsonDatabase.kt b/src/main/kotlin/database/json/bstJsonDatabase.kt
new file mode 100644
index 0000000..bfcd57f
--- /dev/null
+++ b/src/main/kotlin/database/json/bstJsonDatabase.kt
@@ -0,0 +1,63 @@
+package database.json
+
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.databind.SerializationFeature
+import com.fasterxml.jackson.module.kotlin.KotlinModule
+import com.fasterxml.jackson.module.kotlin.readValue
+import java.io.File
+import java.io.FileNotFoundException
+import trees.bstree.BinarySearchTree
+
+
+class JsonRepository(private val dirPath: String) {
+ private val mapper = ObjectMapper().apply {
+ registerModule(KotlinModule())
+ enable(SerializationFeature.INDENT_OUTPUT)
+ }
+ fun getTreeWithIntKey(treeName: String): BinarySearchTree? {
+
+ val json = try {
+ File(dirPath, "${treeName}.json").readText()
+ } catch (_: FileNotFoundException) {
+ return null
+ }
+ return mapper.readValue(json)
+ }
+
+ fun getTreeWithStringKey(treeName: String): BinarySearchTree? {
+
+ val json = try {
+ File(dirPath, "${treeName}.json").readText()
+ } catch (_: FileNotFoundException) {
+ return null
+ }
+ return mapper.readValue(json)
+ }
+
+ fun setTreeWithIntKey(treeName: String, bst: BinarySearchTree){
+ val serialized = mapper.writeValueAsString(bst)
+ val file = File(dirPath, "${treeName}.json")
+ file.writeText(serialized)
+ }
+
+ fun setTreeWithStringKey(treeName: String, bst: BinarySearchTree){
+ val serialized = mapper.writeValueAsString(bst)
+ val file = File(dirPath, "${treeName}.json")
+ file.writeText(serialized)
+ }
+
+ fun getNamesTrees(): Any {
+ val directory = File(dirPath)
+
+ return if (directory.isDirectory) {
+ directory.listFiles()?.filter { it.isFile }?.map { it.name } ?: emptyList()
+ } else {
+ emptyList()
+ }
+ }
+
+ fun remove(treeName: String) {
+ File(dirPath, "${treeName}.json").delete()
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/database/neo4j/Neo4jDataBase.kt b/src/main/kotlin/database/neo4j/Neo4jDataBase.kt
new file mode 100644
index 0000000..c283e6c
--- /dev/null
+++ b/src/main/kotlin/database/neo4j/Neo4jDataBase.kt
@@ -0,0 +1,144 @@
+package database.neo4j
+
+import org.neo4j.driver.*
+import org.neo4j.driver.exceptions.SessionExpiredException
+import org.neo4j.driver.exceptions.value.Uncoercible
+import trees.rbtree.RedBlackTree
+import trees.rbtree.RedBlackTree.Color.*
+import java.io.Closeable
+import java.io.IOException
+
+class Neo4jDataBase() : Closeable {
+ private var driver: Driver? = null
+
+ fun open(uri: String, username: String, password: String) {
+ try {
+ driver = GraphDatabase.driver(uri, AuthTokens.basic(username, password))
+ } catch (exeption: IllegalArgumentException) {
+ throw IOException("Wrong URI", exeption)
+ } catch (exeption: SessionExpiredException) {
+ throw IOException("Session failed", exeption)
+ }
+
+ } override fun close() {
+ driver?.close()
+ }
+ private fun cleanDataBase(tx: TransactionContext) {
+ tx.run("MATCH (n: node) DETACH DELETE n")
+ }
+
+ private fun createNode(sb: StringBuilder, node: RedBlackTree) {
+ with(node) {
+ sb.append(
+ "CREATE (:node {key : \"${node.key}\", " +
+ "value: \"${node.value ?: ""}\", " +
+ "isBlack: ${node.color == BLACK}, " +
+ "lkey: \"${left?.key ?: ""}\", " +
+ "rkey: \"${right?.key ?: ""}\"}) "
+ )
+ left?.let {
+ createNode(sb, it)
+ }
+ right?.let {
+ createNode(sb, it)
+ }
+ }
+ }
+
+ private fun genExportTree(root: RedBlackTree): String {
+ val sb = StringBuilder()
+ createNode(sb, root)
+ return sb.toString()
+ }
+
+ fun loadTree(root: RedBlackTree) {
+ val session = driver?.session() ?: throw IOException("Driver is not open")
+ session.executeWrite { transaction ->
+ cleanDataBase(transaction)
+ transaction.run(genExportTree(root))
+ transaction.run(
+ "MATCH (p: node) " +
+ "MATCH (l: node {key: p.lkey}) " +
+ "CREATE (p)-[:LEFT_CHILD]->(l) " +
+ "REMOVE p.lkey"
+ )
+ transaction.run(
+ "MATCH (p: node) " +
+ "MATCH (r: node {key: p.rkey}) " +
+ "CREATE (p)-[:RIGHT_CHILD]->(r) " +
+ "REMOVE p.rkey"
+ )
+ }
+ session.close()
+ }
+
+ private class NodeKeys(val n: RedBlackTree, val lKey: String?, val rKey: String?)
+
+ private fun parse(nodesRecords: Result) : RedBlackTree? {
+ val NodeKeysMap = mutableMapOf()
+ for (record in nodesRecords) {
+ try {
+ val key = record["key"].asString()
+ val value = record["value"].asString()
+ val node = RedBlackTree()
+ node.key = key
+ node.value = value
+
+ val isBlack = record["isBlack"].asBoolean()
+ node.color = if (isBlack) BLACK else RED
+
+ val lkey = if (record["lKey"].isNull) null else record["lKey"].asString()
+ val rkey = if (record["rKey"].isNull) null else record["rKey"].asString()
+
+ NodeKeysMap[key] = NodeKeys(node, lkey, rkey)
+ } catch (exeption: Uncoercible) {
+ throw IOException("Invalid nodes record in the database", exeption)
+ }
+ }
+ val nodeKeysArray = NodeKeysMap.values.toTypedArray()
+ if (nodeKeysArray.isEmpty())
+ return null
+
+ for (nodeKey in nodeKeysArray) {
+ nodeKey.lKey?.let {
+ nodeKey.n.left = NodeKeysMap[it]?.n
+ NodeKeysMap.remove(it)
+ }
+ nodeKey.n.left?.let {
+ nodeKey.n.left = it
+ it.parent = nodeKey.n
+ }
+
+ nodeKey.rKey?.let {
+ nodeKey.n.right = NodeKeysMap[it]?.n
+ NodeKeysMap.remove(it)
+ }
+ nodeKey.n.right?.let {
+ nodeKey.n.right = it
+ it.parent = nodeKey.n
+ }
+ }
+
+ val root = NodeKeysMap.values.first().n
+ return root
+ }
+
+ private fun unloadNode(transaction: TransactionContext): RedBlackTree? {
+ val nodesRecords = transaction.run(
+ "MATCH (p: RBNode)" +
+ "OPTIONAL MATCH (p)-[:LEFT_CHILD]->(l: node) " +
+ "OPTIONAL MATCH (p)-[:RIGHT_CHILD]->(r: node) " +
+ "RETURN p.isBlack AS isBlack, p.key AS key, p.value AS value, " +
+ "l.key AS lKey, r.key AS rKey"
+ )
+ return parse(nodesRecords)
+ }
+ fun unloadTree(): RedBlackTree? {
+ val session = driver?.session() ?: throw IOException("Driver is not open")
+ val res: RedBlackTree? = session.executeRead { transaction ->
+ unloadNode(transaction)
+ }
+ session.close()
+ return res
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/database/sqlite/SqliteRepAVL.kt b/src/main/kotlin/database/sqlite/SqliteRepAVL.kt
new file mode 100644
index 0000000..776fdc5
--- /dev/null
+++ b/src/main/kotlin/database/sqlite/SqliteRepAVL.kt
@@ -0,0 +1,139 @@
+package database.sqlite
+
+import org.jetbrains.exposed.sql.*
+import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
+import org.jetbrains.exposed.sql.transactions.transaction
+import trees.avltree.AVLTree
+import java.io.File
+
+class SqliteRepAVL(dbName: String) {
+ private var db: Database = Database.connect("jdbc:sqlite:${File(dbName)}", "org.sqlite.JDBC")
+
+ init {
+ transaction(db) {
+ SchemaUtils.create(TreesTable)
+ SchemaUtils.create(SubtreesAvlTable)
+ }
+ }
+
+ /**
+ * return a list of all available tree names in the database
+ */
+ fun getNamesTrees(): List = transaction(db) {
+ val listNames = mutableListOf()
+ TreeDatabase.all().forEach { listNames.add(it.name) }
+ listNames
+ }
+
+ /**
+ * delete the tree and all subtrees from the database
+ */
+ fun remove(treeName: String): Boolean = transaction(db) {
+ val currentTree = TreeDatabase.find(TreesTable.name eq treeName).firstOrNull() ?: return@transaction false
+ AvlSubtree.find(SubtreesAvlTable.tree eq currentTree.id).forEach { it.delete() }
+ currentTree.delete()
+ true
+ }
+
+ /**
+ * find out the type of tree by its name
+ */
+ fun getKeyTypeOfTree(treeName: String): String? =
+ transaction(db) { TreeDatabase.find(TreesTable.name eq treeName).firstOrNull()?.typeOfKey }
+
+ /**
+ * get a tree with an Int type key from the database
+ */
+ fun getTreeWithIntKey(treeName: String): AVLTree = transaction(db) {
+ val root = TreeDatabase.find(TreesTable.name eq treeName).firstOrNull()?.root ?: return@transaction AVLTree()
+ val createdTree = AVLTree()
+ createdTree.key = root.key.toInt()
+ createdTree.value = root.value
+ createdTree.height = root.height.toInt()
+ createdTree.left = root.left?.convertTreeWithIntKey(createdTree)
+ createdTree.right = root.right?.convertTreeWithIntKey(createdTree)
+ createdTree
+ }
+
+ /**
+ * get a tree with a String type key from the database
+ */
+ fun getTreeWithStringKey(treeName: String): AVLTree = transaction(db){
+ val root = TreeDatabase.find(TreesTable.name eq treeName).firstOrNull()?.root ?: return@transaction AVLTree()
+ val createdTree = AVLTree()
+ createdTree.key = root.key
+ createdTree.value = root.value
+ createdTree.height = root.height.toInt()
+ createdTree.left = root.left?.convertTreeWithStringKey(createdTree)
+ createdTree.right = root.right?.convertTreeWithStringKey(createdTree)
+ createdTree
+ }
+
+ /**
+ * An auxiliary function that helps to recursively retrieve a tree
+ * and all its subtrees with an Int key from the database
+ */
+ private fun AvlSubtree.convertTreeWithIntKey(parent: AVLTree? = null): AVLTree {
+ val createdTree = AVLTree()
+ createdTree.key = key.toInt()
+ createdTree.value = value
+ createdTree.height = height.toInt()
+ createdTree.parent = parent
+ createdTree.left = left?.convertTreeWithIntKey(createdTree)
+ createdTree.right = right?.convertTreeWithIntKey(createdTree)
+ return createdTree
+ }
+
+ /**
+ * An auxiliary function that helps to recursively retrieve a tree and
+ * all its subtrees with a String key from the database
+ */
+ private fun AvlSubtree.convertTreeWithStringKey(parent: AVLTree? = null): AVLTree {
+ val createdTree = AVLTree()
+ createdTree.key = key
+ createdTree.value = value
+ createdTree.height = height.toInt()
+ createdTree.parent = parent
+ createdTree.left = left?.convertTreeWithStringKey(createdTree)
+ createdTree.right = right?.convertTreeWithStringKey(createdTree)
+ return createdTree
+ }
+
+ /**
+ * writes a tree with an Int or String type key to the database
+ * in other cases returns exception
+ */
+ fun setTree(treeName: String, currentTree: AVLTree<*, String>, typeKey: String): Unit = transaction(db) {
+ if (typeKey != "Int" && typeKey != "String") throw IllegalStateException("Saving this type of key is not supported in the tree")
+ remove(treeName)
+ val dbTree = TreeDatabase.new {
+ name = treeName
+ typeOfKey = typeKey
+ }
+ val avlRoot = AvlSubtree.new {
+ key = currentTree.key.toString()
+ value = currentTree.value.toString()
+ height = currentTree.height.toString()
+ tree = dbTree
+ left = currentTree.left?.toAvlSubtree(dbTree)
+ right = currentTree.right?.toAvlSubtree(dbTree)
+ }
+ dbTree.root = avlRoot
+
+ }
+
+ /**
+ * recursively writes all subtrees to AvlSubtree table
+ */
+ private fun AVLTree<*, String>.toAvlSubtree(avlTree: TreeDatabase): AvlSubtree =
+ AvlSubtree.new {
+ key = this@toAvlSubtree.key.toString()
+ value = this@toAvlSubtree.value.toString()
+ height = this@toAvlSubtree.height.toString()
+ left = this@toAvlSubtree.left?.toAvlSubtree(avlTree)
+ right = this@toAvlSubtree.right?.toAvlSubtree(avlTree)
+ tree = avlTree
+ }
+
+
+}
diff --git a/src/main/kotlin/database/sqlite/tables.kt b/src/main/kotlin/database/sqlite/tables.kt
new file mode 100644
index 0000000..516a841
--- /dev/null
+++ b/src/main/kotlin/database/sqlite/tables.kt
@@ -0,0 +1,40 @@
+package database.sqlite
+
+import org.jetbrains.exposed.dao.IntEntity
+import org.jetbrains.exposed.dao.IntEntityClass
+import org.jetbrains.exposed.dao.id.EntityID
+import org.jetbrains.exposed.dao.id.IntIdTable
+
+internal object SubtreesAvlTable : IntIdTable("nodes") {
+ val key = varchar("key", 255)
+ val value = varchar("value", 255)
+ val height = varchar("height", 255)
+ val left = reference("left_id", SubtreesAvlTable).nullable()
+ val right = reference("right_id", SubtreesAvlTable).nullable()
+ val tree = reference("tree_id", TreesTable)
+}
+
+internal class AvlSubtree(id: EntityID) : IntEntity(id) {
+ companion object : IntEntityClass(SubtreesAvlTable)
+
+ var key by SubtreesAvlTable.key
+ var value by SubtreesAvlTable.value
+ var height by SubtreesAvlTable.height
+ var left by AvlSubtree optionalReferencedOn SubtreesAvlTable.left
+ var right by AvlSubtree optionalReferencedOn SubtreesAvlTable.right
+ var tree by TreeDatabase referencedOn SubtreesAvlTable.tree
+}
+
+internal object TreesTable : IntIdTable("trees") {
+ val name = varchar("name", 255).uniqueIndex()
+ val root = reference("root_node_id", SubtreesAvlTable).nullable()
+ val typeOfKey = varchar("typeKey", 255)
+}
+
+internal class TreeDatabase(id: EntityID) : IntEntity(id) {
+ companion object : IntEntityClass(TreesTable)
+
+ var name by TreesTable.name
+ var root by AvlSubtree optionalReferencedOn TreesTable.root
+ var typeOfKey by TreesTable.typeOfKey
+}
diff --git a/src/main/kotlin/trees/AbstractBST.kt b/src/main/kotlin/trees/AbstractBST.kt
new file mode 100644
index 0000000..3a055b9
--- /dev/null
+++ b/src/main/kotlin/trees/AbstractBST.kt
@@ -0,0 +1,268 @@
+package trees
+
+import com.fasterxml.jackson.annotation.JsonIgnore
+import trees.bstree.BinarySearchTree
+import kotlin.math.max
+import kotlin.math.pow
+import java.util.Queue
+import java.util.LinkedList
+
+@Suppress("UNCHECKED_CAST")
+abstract class AbstractBST, V, Subtree : AbstractBST> {
+ internal var key: K? = null
+ internal var value: V? = null
+ internal var right: Subtree? = null
+ internal var left: Subtree? = null
+ @JsonIgnore
+ open var parent: Subtree? = null
+
+ protected abstract fun createNewTree(key: K?, value: V?): Subtree
+
+ /**
+ * deletes the desired subtree by key, if there is no key in the tree, it does nothing
+ */
+ open fun remove(key: K) {
+ val needSubtree = searchTree(this as Subtree, key) ?: return
+ removeSubtree(needSubtree)
+ }
+
+
+ /**
+ * if wasTree equal root, then replaces root with newTree
+ */
+ protected fun replaceTreeRoot(wasTree: Subtree, newTree: Subtree?) {
+ val parent = wasTree.parent
+ this.key = newTree?.key
+ this.value = newTree?.value
+ this.right = newTree?.right
+ this.left = newTree?.left
+ this.left?.parent = this as Subtree
+ this.right?.parent = this
+ newTree?.parent = parent
+ }
+
+ /**
+ * a common case of replacing wasTree with newTree
+ * NOTE! does not work for root in AVL tree and Simple BST
+ */
+ protected open fun replaceSubtree(wasTree: Subtree, newTree: Subtree?) {
+ val parent = wasTree.parent
+ if (parent?.left == wasTree) parent.left = newTree
+ else parent?.right = newTree
+ newTree?.parent = parent
+ }
+
+ /**
+ * deletes a subtree by key and returns the deleted subtree
+ */
+ protected fun removeSubtree(givenTree: Subtree): Subtree {
+ return when {
+ givenTree.left != null && givenTree.right != null -> deleteTreeWithTwoSubtrees(givenTree)
+ givenTree.left != null || givenTree.right != null -> deleteTreeWithOneSubtree(givenTree)
+ else -> deleteTreeWithNoSubtree(givenTree)
+ }
+ }
+
+ /**
+ * search for a tree in the givenTree by key
+ */
+ protected fun searchTree(givenTree: Subtree, key: K): Subtree? {
+ if (givenTree.key == null) return null
+ var currentTree: Subtree? = givenTree
+ while (currentTree != null) {
+ val resultCompare =
+ key.compareTo(currentTree.key ?: throw IllegalStateException("this key can not be null"))
+ currentTree = when {
+ resultCompare > 0 -> currentTree.right
+ resultCompare < 0 -> currentTree.left
+ else -> return currentTree
+ }
+ }
+ return null
+ }
+
+ /**
+ * works without overridden for AVL tree and simple BST
+ */
+ protected open fun deleteTreeWithOneSubtree(givenTree: Subtree): Subtree {
+ val necessaryTree = if (givenTree.left == null) givenTree.right else givenTree.left
+ replaceSubtree(givenTree, necessaryTree)
+ return givenTree
+ }
+
+ /**
+ * suitable for all three trees and not overridden
+ */
+ private fun deleteTreeWithTwoSubtrees(givenTree: Subtree): Subtree {
+ val tmpMinimumTree = findMinimumTree(givenTree.right ?: throw Exception("right subtree can not be null"))
+ givenTree.key = tmpMinimumTree.key
+ givenTree.value = tmpMinimumTree.value
+ return removeSubtree(tmpMinimumTree)
+ }
+
+ /**
+ * works without overridden for AVL tree and simple BST
+ */
+ protected open fun deleteTreeWithNoSubtree(givenTree: Subtree): Subtree {
+ replaceSubtree(givenTree, null)
+ return givenTree
+ }
+
+ /**
+ * inserts the key, value, and returns the inserted subtree
+ */
+ protected fun insertTree(key: K, value: V? = null, givenTree: Subtree): Subtree? {
+ if (givenTree.key == null) {
+ givenTree.key = key
+ givenTree.value = value
+ }
+ var currentTree = givenTree
+ while (true) {
+ val resultCompare =
+ key.compareTo(currentTree.key ?: throw IllegalStateException("this key can not be null"))
+ when {
+ resultCompare > 0 -> {
+ if (currentTree.right == null) {
+ val insertedTree = createNewTree(key, value)
+ insertedTree.parent = currentTree
+ currentTree.right = insertedTree
+ return insertedTree
+ }
+ currentTree = currentTree.right ?: throw IllegalStateException("right subtree can not be null")
+ }
+
+ resultCompare < 0 -> {
+ if (currentTree.left == null) {
+ val insertedTree = createNewTree(key, value)
+ insertedTree.parent = currentTree
+ currentTree.left = insertedTree
+ return insertedTree
+ }
+ currentTree = currentTree.left ?: throw IllegalStateException("left subtree can not be null")
+ }
+
+ else -> {
+ currentTree.key = key
+ currentTree.value = value
+ return null
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds a value to the tree by this key, if the key already exists, then overwrites the value
+ */
+ open fun insert(key: K, value: V? = null) {
+ insertTree(key, value, this as Subtree)
+ }
+
+ /**
+ * Returns the found value by key in givenTree, if there is no key, returns null
+ */
+ protected fun findByKey(givenTree: Subtree, key: K): V? {
+ val currentKey = givenTree.key
+ if (currentKey == null || currentKey == key) {
+ return givenTree.value
+ }
+ var currentTree = when {
+ key > currentKey -> givenTree.right
+ else -> givenTree.left
+ }
+ while (currentTree != null) {
+ val resultCompare =
+ key.compareTo(currentTree.key ?: throw IllegalStateException("the current key cannot be null"))
+ currentTree = when {
+ resultCompare > 0 -> currentTree.right
+ resultCompare < 0 -> currentTree.left
+ else -> return currentTree.value
+ }
+ }
+ return null
+ }
+
+ open fun findByKey(key: K): V? {
+ return findByKey(this as Subtree, key)
+ }
+
+ protected open fun rightRotate(givenTree: Subtree): Subtree {
+ val leftSubtree =
+ givenTree.left ?: throw IllegalStateException("The tree must have a left subtree in this rotate")
+ leftSubtree.parent = givenTree.parent
+ if (givenTree.parent?.left == givenTree) givenTree.parent?.left = leftSubtree
+ else givenTree.parent?.right = leftSubtree
+
+ givenTree.left = leftSubtree.right
+ leftSubtree.right?.parent = givenTree
+
+ leftSubtree.right = givenTree
+ givenTree.parent = leftSubtree
+ return leftSubtree
+ }
+
+ protected open fun leftRotate(givenTree: Subtree): Subtree {
+ val rightSubtree =
+ givenTree.right ?: throw IllegalStateException("The tree must have a right subtree in this rotate")
+ rightSubtree.parent = givenTree.parent
+ if (givenTree.parent?.left == givenTree) givenTree.parent?.left = rightSubtree
+ else givenTree.parent?.right = rightSubtree
+
+ givenTree.right = rightSubtree.left
+ rightSubtree.left?.parent = givenTree
+
+ rightSubtree.left = givenTree
+ givenTree.parent = rightSubtree
+ return rightSubtree
+ }
+
+ /**
+ * Searches for the next subtree in order
+ */
+ private fun findMinimumTree(givenTree: Subtree): Subtree {
+ var currentTree = givenTree
+ var leftSubtree = currentTree.left
+ while (leftSubtree != null) {
+ currentTree = leftSubtree
+ leftSubtree = currentTree.left
+ }
+ return currentTree
+ }
+}
+fun , V, Subtree: AbstractBST> height(tree: Subtree?) : Int
+{
+ if (tree == null)
+ return 0
+ else
+ return max(height(tree.left), height(tree.right)) + 1
+}
+
+fun , V, Subtree: AbstractBST> treeLevelOrder(tree: Subtree): MutableList {
+ val treeList = mutableListOf()
+ val queue: Queue = LinkedList()
+ val nullNode = BinarySearchTree()
+ val height = height(tree)
+ var numberOfNodes = 2.0.pow(height).toInt() - 1
+ queue.add(tree)
+ while (numberOfNodes > 0) {
+ val currentTree = queue.poll()
+ if (currentTree == nullNode as Subtree) {
+ numberOfNodes--
+ treeList.add(null)
+ queue.add(nullNode as Subtree)
+ queue.add(nullNode as Subtree)
+ continue
+ }
+ treeList.add(currentTree)
+ if (currentTree.left != null)
+ queue.add(currentTree.left)
+ else
+ queue.add(nullNode as Subtree)
+ if (currentTree.right != null)
+ queue.add(currentTree.right)
+ else
+ queue.add(nullNode as Subtree)
+ numberOfNodes--
+ }
+ return treeList
+}
+
diff --git a/src/main/kotlin/trees/avltree/AVLTree.kt b/src/main/kotlin/trees/avltree/AVLTree.kt
new file mode 100644
index 0000000..3417385
--- /dev/null
+++ b/src/main/kotlin/trees/avltree/AVLTree.kt
@@ -0,0 +1,133 @@
+package trees.avltree
+
+import trees.AbstractBST
+import kotlin.math.max
+
+class AVLTree, V> : AbstractBST>() {
+ internal var height: Int = 1
+
+ override fun createNewTree(key: K?, value: V?): AVLTree {
+ val tmpTree = AVLTree()
+ tmpTree.key = key
+ tmpTree.value = value
+ return tmpTree
+ }
+
+ override fun insert(key: K, value: V?) {
+ var currentTree = insertTree(key, value, this)
+ while (currentTree != null) {
+ balance(currentTree)
+ currentTree = currentTree.parent
+ }
+ }
+
+ override fun replaceSubtree(wasTree: AVLTree, newTree: AVLTree?): Unit =
+ if (wasTree.parent == null) replaceTreeRoot(wasTree, newTree)
+ else super.replaceSubtree(wasTree, newTree)
+
+ override fun remove(key: K) {
+ val necessarySubtree = searchTree(this, key) ?: return
+ val deletedSubtree = removeSubtree(necessarySubtree)
+
+ var currentTree = deletedSubtree.parent
+ while (currentTree != null) {
+ balance(currentTree)
+ currentTree = currentTree.parent
+ }
+ }
+
+ private fun updateHeight(givenTree: AVLTree) {
+ givenTree.height = 1 + max(givenTree.left?.height ?: 0, givenTree.right?.height ?: 0)
+ }
+
+ private fun getBalanceValue(tree: AVLTree?): Int =
+ if (tree == null) 0 else (tree.left?.height ?: 0) - (tree.right?.height ?: 0)
+
+
+ private fun balance(givenTree: AVLTree) {
+ updateHeight(givenTree)
+ val valueBalanceThisTree = getBalanceValue(givenTree)
+ val valueBalanceRightSubtree = getBalanceValue(givenTree.right)
+ val valueBalanceLeftSubtree = getBalanceValue(givenTree.left)
+
+ val flagRoot: Boolean = givenTree.parent == null
+
+ if (valueBalanceThisTree > 1 && valueBalanceLeftSubtree >= 0) {
+ if (flagRoot) givenTree.rightAvlRotateRootTree()
+ else rightRotate(givenTree)
+ }
+ if (valueBalanceThisTree > 1 && valueBalanceLeftSubtree < 0) {
+ leftRotate(givenTree.left ?: throw IllegalStateException("The tree must have a left subtree in this rotate"))
+ if (flagRoot) givenTree.rightAvlRotateRootTree()
+ else rightRotate(givenTree)
+ }
+ if (valueBalanceThisTree < -1 && valueBalanceRightSubtree <= 0) {
+ if (flagRoot) givenTree.leftAvlRotateRootTree()
+ else leftRotate(givenTree)
+ }
+ if (valueBalanceThisTree < -1 && valueBalanceRightSubtree > 0) {
+ rightRotate(givenTree.right ?: throw IllegalStateException("The tree must have a right subtree in this rotate"))
+ if (flagRoot) givenTree.leftAvlRotateRootTree()
+ else leftRotate(givenTree)
+ }
+ }
+
+ /**
+ * right turn for the case when the tree is the root
+ */
+ private fun rightAvlRotateRootTree() {
+ val leftSubtree = this.left ?: throw IllegalStateException("The tree must have a left subtree in this rotate")
+ val thisTree = AVLTree()
+ thisTree.value = this.value
+ thisTree.key = this.key
+ thisTree.right = this.right
+ thisTree.left = leftSubtree.right
+ thisTree.right?.parent = thisTree
+ thisTree.parent = this
+ thisTree.left?.parent = thisTree
+ this.value = leftSubtree.value
+ this.key = leftSubtree.key
+ this.left = leftSubtree.left
+ this.left?.parent = this
+ this.right = thisTree
+ this.right?.let { updateHeight(it) }
+ updateHeight(this)
+ }
+
+
+ /**
+ * left turn for the case when the tree is the root
+ */
+ private fun leftAvlRotateRootTree() {
+ val rightSubtree = this.right ?: throw IllegalStateException("The tree must have a right subtree in this rotate")
+ val thisTree = AVLTree()
+ thisTree.value = this.value
+ thisTree.key = this.key
+ thisTree.left = this.left
+ thisTree.right = rightSubtree.left
+ thisTree.parent = this
+ thisTree.left?.parent = thisTree
+ thisTree.right?.parent = thisTree
+ this.value = rightSubtree.value
+ this.key = rightSubtree.key
+ this.right = rightSubtree.right
+ this.right?.parent = this
+ this.left = thisTree
+ this.left?.let { updateHeight(it) }
+ updateHeight(this)
+ }
+
+ override fun rightRotate(givenTree: AVLTree): AVLTree {
+ val returnedRightRotateTree = super.rightRotate(givenTree)
+ updateHeight(givenTree)
+ updateHeight(returnedRightRotateTree)
+ return returnedRightRotateTree
+ }
+
+ override fun leftRotate(givenTree: AVLTree): AVLTree {
+ val returnedLeftRotateTree = super.leftRotate(givenTree)
+ updateHeight(givenTree)
+ updateHeight(returnedLeftRotateTree)
+ return returnedLeftRotateTree
+ }
+}
diff --git a/src/main/kotlin/trees/bstree/BinarySearchTree.kt b/src/main/kotlin/trees/bstree/BinarySearchTree.kt
new file mode 100644
index 0000000..4f185a8
--- /dev/null
+++ b/src/main/kotlin/trees/bstree/BinarySearchTree.kt
@@ -0,0 +1,16 @@
+package trees.bstree
+
+import trees.AbstractBST
+
+class BinarySearchTree, V> : AbstractBST>() {
+ override fun createNewTree(key: K?, value: V?): BinarySearchTree {
+ val tmpTree = BinarySearchTree()
+ tmpTree.key = key
+ tmpTree.value = value
+ return tmpTree
+ }
+
+ override fun replaceSubtree(wasTree: BinarySearchTree, newTree: BinarySearchTree?): Unit =
+ if (wasTree.parent == null) replaceTreeRoot(wasTree, newTree)
+ else super.replaceSubtree(wasTree, newTree)
+}
diff --git a/src/main/kotlin/trees/rbtree/RedBlackTree.kt b/src/main/kotlin/trees/rbtree/RedBlackTree.kt
new file mode 100644
index 0000000..2af21f9
--- /dev/null
+++ b/src/main/kotlin/trees/rbtree/RedBlackTree.kt
@@ -0,0 +1,246 @@
+package trees.rbtree
+
+import trees.AbstractBST
+
+class RedBlackTree, V> : AbstractBST>() {
+ enum class Color {
+ RED, BLACK
+ }
+
+ internal var root = this
+ internal var color: Color = Color.BLACK
+
+ override fun createNewTree(key: K?, value: V?): RedBlackTree {
+ val tmp = RedBlackTree()
+ tmp.value = value
+ tmp.key = key
+ return tmp
+ }
+
+ override fun findByKey(key: K): V? {
+ return findByKey(root, key)
+ }
+
+ override fun replaceSubtree(wasTree: RedBlackTree, newTree: RedBlackTree?) {
+ val parent = wasTree.parent
+ if (parent == null) {
+ if (newTree == null) {
+ root.key = null
+ root.value = null
+ root.left = null
+ root.right = null
+ }
+ else {
+ root = newTree
+ }
+ } else if (parent.left == wasTree) {
+ parent.left = newTree
+ } else {
+ parent.right = newTree
+ }
+ newTree?.parent = wasTree.parent
+ }
+
+ private fun reverseColor() {
+ this.color = if (this.color == Color.BLACK) Color.RED else Color.BLACK
+ }
+
+ private fun getSibling(givenTree: RedBlackTree): RedBlackTree? {
+ val currentParent = givenTree.parent ?: return null
+ if (currentParent.left == givenTree) return currentParent.right
+ return currentParent.left
+ }
+
+ private fun getUncle(givenTree: RedBlackTree): RedBlackTree? {
+ val currentParent = givenTree.parent ?: return null
+ return getSibling(currentParent)
+ }
+
+ /**
+ * you can read more about balancing after adding and after removing a subtree here
+ * https://neerc.ifmo.ru/wiki/
+ */
+ private fun balanceAfterInsert(givenTree: RedBlackTree): RedBlackTree {
+ var currentTree = givenTree
+
+ while (currentTree.parent != null && currentTree.parent?.color == Color.RED) {
+ val currentParent = currentTree.parent ?: throw IllegalStateException("the parent must not be null")
+ val currentGrandParent = currentParent.parent ?: throw IllegalStateException("grand parent must not be null")
+ val currentUncle = getUncle(currentTree)
+ if (currentUncle?.color == Color.RED) {
+ currentParent.reverseColor()
+ currentGrandParent.reverseColor()
+ currentUncle.reverseColor()
+ currentTree = currentGrandParent
+ } else {
+ if (currentGrandParent.left == currentParent) {
+ if (currentTree == currentParent.right)
+ leftRotate(currentParent)
+ currentTree = rightRotate(currentGrandParent)
+ currentTree.right?.reverseColor()
+ } else {
+ if (currentTree == currentParent.left)
+ rightRotate(currentParent)
+ currentTree = leftRotate(currentGrandParent)
+ currentTree.left?.reverseColor()
+ }
+ currentTree.reverseColor()
+ break
+ }
+ }
+
+ if (currentTree.parent == null && currentTree.color == Color.RED) {
+ currentTree.reverseColor()
+ return currentTree
+ }
+
+ while (currentTree.parent != null) {
+ currentTree = currentTree.parent ?: throw IllegalStateException("current tree must have parent")
+ }
+ return currentTree
+ }
+
+ private fun balanceAfterRemove(givenTree: RedBlackTree): RedBlackTree {
+ var currentTree = givenTree
+ while (currentTree.parent != null && currentTree.color == Color.BLACK) {
+ val currentParent = currentTree.parent ?: throw IllegalStateException("parent can not be null")
+ if (currentParent.left == currentTree) {
+ val rightSibling = currentParent.right ?: throw IllegalStateException("parent must have right child")
+ if (currentParent.color == Color.RED) {
+ if (rightSibling.left?.color == Color.RED || rightSibling.right?.color == Color.RED) {
+ currentParent.reverseColor()
+ if (rightSibling.left?.color == Color.RED) {
+ rightRotate(rightSibling)
+ } else {
+ rightSibling.reverseColor()
+ rightSibling.right?.reverseColor()
+ }
+ currentTree = leftRotate(currentParent)
+ } else {
+ currentParent.reverseColor()
+ rightSibling.reverseColor()
+ }
+ break
+ } else {
+ if (rightSibling.color == Color.RED) {
+ var leftChildOfRightSibling = rightSibling.left ?: throw IllegalStateException("left child of right sibling can not be null")
+ if (leftChildOfRightSibling.left?.color == Color.RED || leftChildOfRightSibling.right?.color == Color.RED) {
+ if (leftChildOfRightSibling.right == null || leftChildOfRightSibling.right?.color == Color.BLACK) {
+ leftChildOfRightSibling.reverseColor()
+ leftChildOfRightSibling.left?.reverseColor()
+ leftChildOfRightSibling = rightRotate(leftChildOfRightSibling)
+ }
+ leftChildOfRightSibling.right?.reverseColor()
+ rightRotate(rightSibling)
+ } else {
+ rightSibling.reverseColor()
+ leftChildOfRightSibling.reverseColor()
+ }
+ currentTree = leftRotate(currentParent)
+ break
+ } else {
+ if (rightSibling.left?.color == Color.RED || rightSibling.right?.color == Color.RED) {
+ if (rightSibling.left?.color == Color.RED) {
+ rightSibling.left?.reverseColor()
+ rightRotate(rightSibling)
+ } else {
+ rightSibling.right?.reverseColor()
+ }
+ currentTree = leftRotate(currentParent)
+ break
+ } else {
+ rightSibling.reverseColor()
+ currentTree = currentParent
+ }
+ }
+ }
+ } else {
+ val leftSibling = currentParent.left ?: throw IllegalStateException("parent must have left child")
+ if (currentParent.color == Color.RED) {
+ if (leftSibling.left?.color == Color.RED || leftSibling.right?.color == Color.RED) {
+ currentParent.reverseColor()
+ if (leftSibling.right?.color == Color.RED) {
+ leftRotate(leftSibling)
+ } else {
+ leftSibling.reverseColor()
+ leftSibling.left?.reverseColor()
+ }
+ currentTree = rightRotate(currentParent)
+ } else {
+ currentParent.reverseColor()
+ leftSibling.reverseColor()
+ }
+ break
+ } else {
+ if (leftSibling.color == Color.RED) {
+ var rightChildOfLeftSibling = leftSibling.right ?: throw IllegalStateException("right child of left sibling can not be null")
+ if (rightChildOfLeftSibling.left?.color == Color.RED || rightChildOfLeftSibling.right?.color == Color.RED) {
+ if (rightChildOfLeftSibling.left == null || rightChildOfLeftSibling.left?.color == Color.BLACK) {
+ rightChildOfLeftSibling.reverseColor()
+ rightChildOfLeftSibling.right?.reverseColor()
+ rightChildOfLeftSibling = leftRotate(rightChildOfLeftSibling)
+ }
+ rightChildOfLeftSibling.left?.reverseColor()
+ leftRotate(leftSibling)
+ } else {
+ leftSibling.reverseColor()
+ rightChildOfLeftSibling.reverseColor()
+ }
+ currentTree = rightRotate(currentParent)
+ break
+ } else {
+ if (leftSibling.left?.color == Color.RED || leftSibling.right?.color == Color.RED) {
+ if (leftSibling.right?.color == Color.RED) {
+ leftSibling.right?.reverseColor()
+ leftRotate(leftSibling)
+ } else {
+ leftSibling.left?.reverseColor()
+ }
+ currentTree = rightRotate(currentParent)
+ break
+ } else {
+ leftSibling.reverseColor()
+ currentTree = currentParent
+ }
+ }
+ }
+ }
+ }
+
+ while (currentTree.parent != null) {
+ currentTree = currentTree.parent ?: throw IllegalStateException("current tree must have parent")
+ }
+
+ return currentTree
+ }
+
+ override fun insert(key: K, value: V?) {
+ val insertedTree = insertTree(key, value, root) ?: return
+ insertedTree.color = Color.RED
+ root = balanceAfterInsert(insertedTree)
+ }
+
+ override fun deleteTreeWithNoSubtree(givenTree: RedBlackTree): RedBlackTree {
+ if (givenTree.color == Color.BLACK) {
+ root = balanceAfterRemove(givenTree)
+ }
+ replaceSubtree(givenTree, null)
+ return givenTree
+ }
+
+ override fun deleteTreeWithOneSubtree(givenTree: RedBlackTree): RedBlackTree {
+ if (givenTree.left != null) {
+ givenTree.left?.reverseColor()
+ replaceSubtree(givenTree, givenTree.left)
+ } else {
+ givenTree.right?.reverseColor()
+ replaceSubtree(givenTree, givenTree.right)
+ }
+ return givenTree
+ }
+
+ override fun remove(key: K) {
+ val necessaryTree = searchTree(root, key) ?: return
+ removeSubtree(necessaryTree)
+ }
+}
diff --git a/src/main/resources/log4j2.yaml b/src/main/resources/log4j2.yaml
new file mode 100644
index 0000000..021e84d
--- /dev/null
+++ b/src/main/resources/log4j2.yaml
@@ -0,0 +1,21 @@
+Configuration:
+ status: warn
+ Appenders:
+ Console:
+ - name: Console_Info
+ target: SYSTEM_ERR
+ PatternLayout:
+ Pattern: "%highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=green, TRACE=green} %style{[%t]}{white} %style{%-30.30c{1.}}{white} %style{ ↘ %m%n%ex}{white}"
+ #Pattern: "%style{%d{yyyy-MM-dd HH:mm:ss.SSS}}{white} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red, ERROR=red, WARN=yellow, INFO=green, DEBUG=green, TRACE=green} %style{[%t]}{white} %style{%-30.30c{1.}}{cyan} %style{:%m%n%ex}{white}"
+ File:
+ append: false
+ name: File_Appender
+ fileName: application.log
+ PatternLayout:
+ Pattern: "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"
+ Loggers:
+ Root:
+ level: info
+ AppenderRef:
+ - ref: Console_Info
+ - ref: File_Appender
\ No newline at end of file
diff --git a/src/test/kotlin/database/sqlite/SqliteRepAVLTest.kt b/src/test/kotlin/database/sqlite/SqliteRepAVLTest.kt
new file mode 100644
index 0000000..3142080
--- /dev/null
+++ b/src/test/kotlin/database/sqlite/SqliteRepAVLTest.kt
@@ -0,0 +1,166 @@
+package database.sqlite
+
+import org.junit.jupiter.api.*
+import org.junit.jupiter.api.Assertions.*
+import trees.avltree.AVLTree
+import java.io.File
+
+@TestMethodOrder(MethodOrderer.OrderAnnotation::class)
+class SqliteRepAVLTest {
+ private val repo = SqliteRepAVL("src/main/kotlin/database/sqlite/TestDatabase")
+
+ @Test
+ @Order(1)
+ fun `save avl tree Int key in database #1`() {
+ val tree = AVLTree()
+ tree.insert(10, "a")
+ tree.insert(5, "b")
+ tree.insert(15, "c")
+ repo.setTree("Avl1", tree, "Int")
+ }
+
+ @Test
+ @Order(2)
+ fun `save avl tree Int key in database #2`() {
+ val tree = AVLTree()
+ tree.insert(15, "a")
+ tree.insert(10, "b")
+ tree.insert(20, "c")
+ repo.setTree("Avl2", tree, "Int")
+ }
+
+ @Test
+ @Order(3)
+ fun `get names trees`() {
+ val names = repo.getNamesTrees()
+ assertEquals(names.size, 2)
+ assertEquals(names[0], "Avl1")
+ assertEquals(names[1], "Avl2")
+ }
+
+ @Test
+ @Order(4)
+ fun `save avl tree String key in database #1`() {
+ val tree = AVLTree()
+ tree.insert("b")
+ tree.insert("a")
+ tree.insert("c")
+ repo.setTree("Avl3", tree, "String")
+ }
+
+ @Test
+ @Order(5)
+ fun `save avl tree String key in database #2`() {
+ val tree = AVLTree()
+ tree.insert("c")
+ tree.insert("d")
+ tree.insert("b")
+ repo.setTree("Avl4", tree, "String")
+ }
+
+ @Test
+ @Order(6)
+ fun `get avl tree Int key in database #1`() {
+ val tree = repo.getTreeWithIntKey("Avl1")
+ // Check correct height tree
+ assertEquals(tree.height, 2)
+ assertEquals(tree.right?.height, 1)
+ assertEquals(tree.left?.height, 1)
+ // Check correct value in tree
+ assertEquals(tree.value, "a")
+ assertEquals(tree.right?.value, "c")
+ assertEquals(tree.left?.value, "b")
+ // Check correct key in tree
+ assertEquals(tree.key, 10)
+ assertEquals(tree.right?.key, 15)
+ assertEquals(tree.left?.key, 5)
+ // Check correct leaf
+ assertNull(tree.right?.right)
+ assertNull(tree.right?.left)
+ assertNull(tree.left?.left)
+ assertNull(tree.left?.right)
+ }
+
+ @Test
+ @Order(7)
+ fun `get avl tree Int key in database #2`() {
+ val tree = repo.getTreeWithIntKey("Avl2")
+ // Check correct height tree
+ assertEquals(tree.height, 2)
+ assertEquals(tree.right?.height, 1)
+ assertEquals(tree.left?.height, 1)
+ // Check correct value in tree
+ assertEquals(tree.value, "a")
+ assertEquals(tree.right?.value, "c")
+ assertEquals(tree.left?.value, "b")
+ // Check correct key in tree
+ assertEquals(tree.key, 15)
+ assertEquals(tree.right?.key, 20)
+ assertEquals(tree.left?.key, 10)
+ // Check correct leaf
+ assertNull(tree.right?.right)
+ assertNull(tree.right?.left)
+ assertNull(tree.left?.left)
+ assertNull(tree.left?.right)
+ }
+
+ @Test
+ @Order(8)
+ fun `get avl tree String key in database #1`() {
+ val tree = repo.getTreeWithStringKey("Avl3")
+ // Check correct height tree
+ assertEquals(tree.height, 2)
+ assertEquals(tree.right?.height, 1)
+ assertEquals(tree.left?.height, 1)
+ // Check correct key in tree
+ assertEquals(tree.key, "b")
+ assertEquals(tree.right?.key, "c")
+ assertEquals(tree.left?.key, "a")
+ // Check correct leaf
+ assertNull(tree.right?.right)
+ assertNull(tree.right?.left)
+ assertNull(tree.left?.left)
+ assertNull(tree.left?.right)
+ }
+
+ @Test
+ @Order(9)
+ fun `get names tree after get tree in database`() {
+ val names = repo.getNamesTrees()
+ assertEquals(names.size, 4)
+ assertEquals(names[0], "Avl1")
+ assertEquals(names[1], "Avl2")
+ assertEquals(names[2], "Avl3")
+ assertEquals(names[3], "Avl4")
+ }
+
+ @Test
+ @Order(10)
+ fun `test get type key of tree`() {
+ assertEquals(repo.getKeyTypeOfTree("Avl1"), "Int")
+ assertEquals(repo.getKeyTypeOfTree("Avl3"), "String")
+ }
+
+ @Test
+ @Order(11)
+ fun `correct deletion from the database`() {
+ repo.remove("Avl1")
+ repo.remove("Avl3")
+ repo.remove("non-Exist")
+ val names = repo.getNamesTrees()
+ assertEquals(names.size, 2)
+ assertEquals(names[0], "Avl2")
+ assertEquals(names[1], "Avl4")
+ }
+
+ companion object {
+ @JvmStatic
+ @AfterAll
+ fun `delete testing database`(): Unit {
+ val file = File("src/main/kotlin/database/sqlite/TestDatabase")
+
+ val resultDelete = file.delete()
+ assertTrue(resultDelete)
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/test/kotlin/trees/avltree/AVLTreeTest.kt b/src/test/kotlin/trees/avltree/AVLTreeTest.kt
new file mode 100644
index 0000000..5e76f5b
--- /dev/null
+++ b/src/test/kotlin/trees/avltree/AVLTreeTest.kt
@@ -0,0 +1,295 @@
+package trees.avltree
+
+import org.junit.jupiter.api.Assertions.*
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.TestInstance
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.MethodSource
+import trees.correctReferencesParents
+import trees.treeKeysCorrectOrder
+import java.util.stream.Stream
+import kotlin.math.abs
+import kotlin.math.max
+import kotlin.random.Random
+
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class AvlTreeTest {
+ private fun checkAVLInvariant(tree: AVLTree): Boolean {
+
+ /**
+ * recursively checks that the height of the right and left subtree differs by less than 1
+ */
+ fun isBalanced(currentTree: AVLTree?): Int? {
+ if (currentTree == null) return 0
+ val heightLeft = isBalanced(currentTree.left) ?: return null
+ val heightRight = isBalanced(currentTree.right) ?: return null
+
+ if (abs(heightLeft - heightRight) > 1) return null
+ return max(heightLeft, heightRight) + 1
+ }
+
+ return (isBalanced(tree) != null) && treeKeysCorrectOrder(tree) && correctReferencesParents(tree)
+ }
+
+ private val randomizer = Random(87)
+ private val keys = Array(1000) { randomizer.nextInt() }.distinct()
+ private val values = Array(keys.size) { randomizer.nextInt() }.distinct()
+ private lateinit var tree: AVLTree
+
+ @BeforeEach
+ fun recreateTree() {
+ tree = AVLTree()
+ }
+
+ private fun getData() = Stream.of(
+ Pair(10, 68),
+ Pair(10, 89),
+ Pair(1000, 211),
+ Pair(1000, 42),
+ Pair(100000, 20),
+ Pair(100000, 1337)
+ )
+
+ @ParameterizedTest
+ @MethodSource("getData")
+ fun `insert, remove and find values`(currentData: Pair) {
+ val arraySize = currentData.first
+ val seed = currentData.second
+
+ val currentRandomizer = Random(seed)
+ val keys = List(arraySize) { currentRandomizer.nextInt() }.distinct()
+ val values = List(keys.size) { currentRandomizer.nextInt() }
+ val map = mutableMapOf()
+ for (i in keys.indices) {
+ map[keys[i]] = values[i]
+ }
+
+ for (key in map.keys) {
+ tree.insert(key)
+ }
+ assertTrue(checkAVLInvariant(tree))
+ for (key in map.keys.shuffled()) {
+ tree.remove(key)
+ assertNull(tree.findByKey(key))
+ }
+ assertTrue(checkAVLInvariant(tree))
+ }
+
+ @Test
+ fun `invariant and find after deletion`() {
+ for (i in keys.indices) tree.insert(keys[i], values[i])
+ val leftRange = (Math.random() * keys.size).toInt()
+ val rightRange = (Math.random() * (keys.size - leftRange + 1)).toInt() + leftRange
+ for (i in leftRange until rightRange) {
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ tree.remove(keys[i])
+ assertTrue(checkAVLInvariant(tree))
+ assertNull(tree.findByKey(keys[i]))
+ }
+ }
+
+ @Test
+ fun `invariant and find after insertion`() {
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkAVLInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ }
+
+ @Test
+ fun `invariant after insertion duplicates`() {
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkAVLInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ val values = Array(keys.size) { randomizer.nextInt() }
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkAVLInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ }
+
+ @Test
+ fun `find by non-existent key and return null`() {
+ tree.insert(10)
+ assertNull(tree.findByKey(5))
+ assertNull(tree.findByKey(100))
+ }
+
+ @Test
+ fun `overwriting the key value`() {
+ tree.insert(10, 10)
+ assertEquals(tree.value, 10)
+ tree.insert(10, 20)
+ assertEquals(tree.value, 20)
+ }
+
+ @Test
+ fun `removing a non-existent key`() {
+ val keys = listOf(10, 20, 30)
+ keys.forEach { tree.insert(it, it) }
+ val deletedKeys = listOf(2, 40, 25)
+ deletedKeys.forEach { tree.remove(it) }
+ keys.forEach { assertEquals(tree.findByKey(it), it) }
+ deletedKeys.forEach { assertNull(tree.findByKey(it)) }
+ }
+
+ @Test
+ fun `right rotate testing`() {
+ /*
+ constructed tree before right rotate:
+ 10
+ / \
+ 8 11
+ / \
+ 7 9
+ */
+ tree.insert(10)
+ tree.insert(11)
+ tree.insert(8)
+ tree.insert(9)
+ tree.insert(7)
+ assertEquals(tree.key, 10)
+ assertEquals(tree.left?.key, 8)
+ assertEquals(tree.left?.left?.key, 7)
+ assertEquals(tree.left?.right?.key, 9)
+ assertEquals(tree.right?.key, 11)
+ tree.remove(11)
+ /*
+ constructed tree after remove `11`:
+ 8
+ / \
+ 7 10
+ /
+ 9
+ */
+ assertEquals(tree.key, 8)
+ assertEquals(tree.left?.key, 7)
+ assertEquals(tree.right?.key, 10)
+ assertEquals(tree.right?.left?.key, 9)
+ assertTrue(checkAVLInvariant(tree))
+ }
+
+ @Test
+ fun `left rotate testing`() {
+ /*
+ constructed tree before left rotate:
+ 10
+ / \
+ 8 12
+ / \
+ 11 13
+
+ */
+ tree.insert(10)
+ tree.insert(12)
+ tree.insert(8)
+ tree.insert(11)
+ tree.insert(13)
+ assertEquals(tree.key, 10)
+ assertEquals(tree.left?.key, 8)
+ assertEquals(tree.right?.key, 12)
+ assertEquals(tree.right?.left?.key, 11)
+ assertEquals(tree.right?.right?.key, 13)
+ tree.remove(8)
+ /*
+ constructed tree after remove `8`:
+ 12
+ / \
+ 10 13
+ \
+ 11
+
+ */
+ assertEquals(tree.key, 12)
+ assertEquals(tree.left?.key, 10)
+ assertEquals(tree.left?.right?.key, 11)
+ assertEquals(tree.right?.key, 13)
+ assertTrue(checkAVLInvariant(tree))
+ }
+
+ @Test
+ fun `big right rotate testing`() {
+ tree.insert(10)
+ tree.insert(15)
+ tree.insert(7)
+ tree.insert(9)
+ tree.insert(6)
+ /*
+ constructed tree:
+ 10
+ / \
+ 7 15
+ / \
+ 6 9
+ /
+ +8?
+ */
+ assertEquals(tree.key, 10)
+ assertEquals(tree.right?.key, 15)
+ assertEquals(tree.left?.key, 7)
+ assertEquals(tree.left?.left?.key, 6)
+ assertEquals(tree.left?.right?.key, 9)
+ tree.insert(8)
+ /*
+ constructed tree:
+ 9
+ / \
+ 7 10
+ / \ \
+ 6 8 15
+ */
+ assertEquals(tree.key, 9)
+ assertEquals(tree.right?.key, 10)
+ assertEquals(tree.right?.right?.key, 15)
+ assertEquals(tree.left?.key, 7)
+ assertEquals(tree.left?.left?.key, 6)
+ assertEquals(tree.left?.right?.key, 8)
+ assertTrue(checkAVLInvariant(tree))
+ }
+
+ @Test
+ fun `big left rotate testing`() {
+ tree.insert(10)
+ tree.insert(8)
+ tree.insert(20)
+ tree.insert(15)
+ tree.insert(22)
+ /*
+ constructed tree before insert 16:
+ 10
+ / \
+ 8 20
+ / \
+ 15 22
+ \
+ +16?
+
+ */
+ assertEquals(tree.key, 10)
+ assertEquals(tree.left?.key, 8)
+ assertEquals(tree.right?.key, 20)
+ assertEquals(tree.right?.left?.key, 15)
+ assertEquals(tree.right?.right?.key, 22)
+ tree.insert(16)
+ /*
+ constructed tree after insert 16:
+ 15
+ / \
+ 10 20
+ / / \
+ 8 16 22
+ */
+ assertEquals(tree.key, 15)
+ assertEquals(tree.right?.key, 20)
+ assertEquals(tree.left?.key, 10)
+ assertEquals(tree.left?.left?.key, 8)
+ assertEquals(tree.right?.right?.key, 22)
+ assertEquals(tree.right?.left?.key, 16)
+ assertTrue(checkAVLInvariant(tree))
+ }
+}
diff --git a/src/test/kotlin/trees/bstree/BinarySearchTreeTest.kt b/src/test/kotlin/trees/bstree/BinarySearchTreeTest.kt
new file mode 100644
index 0000000..86babe9
--- /dev/null
+++ b/src/test/kotlin/trees/bstree/BinarySearchTreeTest.kt
@@ -0,0 +1,189 @@
+package trees.bstree
+
+import org.junit.jupiter.api.Assertions.*
+import org.junit.jupiter.api.*
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.MethodSource
+import trees.correctReferencesParents
+import trees.treeKeysCorrectOrder
+import java.util.stream.Stream
+import kotlin.random.Random
+
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class BinarySearchTreeTest {
+
+ private fun checkBSTInvariant(tree: BinarySearchTree): Boolean {
+ return treeKeysCorrectOrder(tree) && correctReferencesParents(tree)
+ }
+
+ private val randomizer = Random(42)
+ private val keys = Array(1000) { randomizer.nextInt() }.distinct()
+ private val values = Array(keys.size) { randomizer.nextInt() }
+ private lateinit var tree: BinarySearchTree
+
+ @BeforeEach
+ fun recreateTree() {
+ tree = BinarySearchTree()
+ }
+
+ private fun getData() = Stream.of(
+ Pair(10, 68),
+ Pair(10, 89),
+ Pair(1000, 211),
+ Pair(1000, 42),
+ Pair(100000, 13),
+ Pair(100000, 1337)
+ )
+
+ @ParameterizedTest
+ @MethodSource("getData")
+ fun `insert, remove and find values`(currentData: Pair) {
+ val arraySize = currentData.first
+ val seed = currentData.second
+
+ val currentRandomizer = Random(seed)
+ val keys = List(arraySize) { currentRandomizer.nextInt() }
+ val values = List(arraySize) { currentRandomizer.nextInt() }
+ val map = mutableMapOf()
+ for (i in 0 until arraySize) {
+ map[keys[i]] = values[i]
+ }
+
+ for (key in map.keys) {
+ tree.insert(key)
+ }
+ assertTrue(checkBSTInvariant(tree))
+ for (key in map.keys.shuffled()) {
+ tree.remove(key)
+ assertNull(tree.findByKey(key))
+ }
+ assertTrue(checkBSTInvariant(tree))
+ }
+
+
+ @Test
+ fun `invariant and find after deletion`() {
+ for (i in keys.indices) tree.insert(keys[i], values[i])
+ val leftRange = (Math.random() * keys.size).toInt()
+ val rightRange = (Math.random() * (keys.size - leftRange + 1)).toInt() + leftRange
+ for (i in leftRange until rightRange) {
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ tree.remove(keys[i])
+ assertTrue(checkBSTInvariant(tree))
+ assertNull(tree.findByKey(keys[i]))
+ }
+ }
+
+ @Test
+ fun `invariant and find after insertion`() {
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkBSTInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ }
+
+ @Test
+ fun `invariant after insertion duplicates`() {
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkBSTInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ val values = Array(keys.size) { randomizer.nextInt() }
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkBSTInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ }
+
+ @Test
+ fun `overwriting the key value`() {
+ tree.insert(10, 10)
+ assertEquals(tree.value, 10)
+ tree.insert(10, 20)
+ assertEquals(tree.value, 20)
+ }
+
+ @Test
+ fun `find by non-existent key and return null`() {
+ tree.insert(10, 10)
+ assertNull(tree.findByKey(5))
+ assertNull(tree.findByKey(100))
+ }
+
+ @Test
+ fun `removing a non-existent key`() {
+ val keys = listOf(10, 20, 30)
+ keys.forEach { tree.insert(it, it) }
+ val deletedKeys = listOf(2, 40, 25)
+ deletedKeys.forEach { tree.remove(it) }
+ keys.forEach { assertEquals(tree.findByKey(it), it) }
+ deletedKeys.forEach { assertNull(tree.findByKey(it)) }
+ }
+
+ @Test
+ fun `removing the root with the right subtree only`() {
+ val keys = listOf(10, 20, 30)
+ keys.forEach { tree.insert(it) }
+ tree.remove(10)
+ assertEquals(tree.key, 20)
+ assertEquals(tree.right?.key, 30)
+ }
+
+ @Test
+ fun `removing the root with the left subtree only`() {
+ val keys = listOf(30, 20, 10)
+ keys.forEach { tree.insert(it) }
+ tree.remove(30)
+ assertEquals(tree.key, 20)
+ assertEquals(tree.left?.key, 10)
+ }
+
+ @Test
+ fun `removing a root with left and right subtrees`() {
+ val keys = listOf(10, 20, 5, 1)
+ keys.forEach { tree.insert(it) }
+ tree.remove(10)
+ assertEquals(tree.key, 20)
+ assertNull(tree.right)
+ assertEquals(tree.left?.key, 5)
+ assertEquals(tree.left?.left?.key, 1)
+ }
+
+ @Test
+ fun `removing a tree with the left subtree only`() {
+ val keys = listOf(10, 20, 15, 14)
+ keys.forEach { tree.insert(it) }
+ tree.remove(20)
+ assertEquals(tree.key, 10)
+ assertNull(tree.left)
+ assertEquals(tree.right?.key, 15)
+ assertEquals(tree.right?.left?.key, 14)
+ }
+
+ @Test
+ fun `removing a tree with the right subtree only`() {
+ val keys = listOf(20, 15, 17, 16, 18)
+ keys.forEach { tree.insert(it) }
+ tree.remove(15)
+ assertEquals(tree.key, 20)
+ assertNull(tree.right)
+ assertEquals(tree.left?.key, 17)
+ assertEquals(tree.left?.left?.key, 16)
+ assertEquals(tree.left?.right?.key, 18)
+ }
+
+ @Test
+ fun `removing a tree with left and right subtrees`() {
+ val keys = listOf(10, 20, 15, 30, 25, 50)
+ keys.forEach { tree.insert(it) }
+ tree.remove(20)
+ assertEquals(tree.key, 10)
+ assertEquals(tree.right?.key, 25)
+ assertEquals(tree.right?.left?.key, 15)
+ assertEquals(tree.right?.right?.key, 30)
+ assertEquals(tree.right?.right?.right?.key, 50)
+ }
+}
diff --git a/src/test/kotlin/trees/heplerTests.kt b/src/test/kotlin/trees/heplerTests.kt
new file mode 100644
index 0000000..6c839ce
--- /dev/null
+++ b/src/test/kotlin/trees/heplerTests.kt
@@ -0,0 +1,42 @@
+package trees
+
+/**
+ * checks if the tree keys are ascending
+ */
+fun , V, Subtree: AbstractBST> treeKeysCorrectOrder(tree: Subtree): Boolean {
+ val listKeys = traverseInOrderTree(tree)
+ for (i in 0 until listKeys.size - 1) {
+ val prevKey = listKeys[i].key ?: throw IllegalStateException("prev key can not be null")
+ val currentKey = listKeys[i + 1].key ?: throw IllegalStateException("current key can not be null")
+ if (prevKey >= currentKey)
+ return false
+ }
+ return true
+}
+
+/**
+ * checking that links to parents are specified correctly
+ */
+fun , V, Subtree: AbstractBST> correctReferencesParents(tree: Subtree?, parent: Subtree? = null): Boolean {
+ if (tree == null) return true
+ return (tree.parent == parent) && correctReferencesParents(tree.left, tree) && correctReferencesParents(tree.right, tree)
+}
+
+
+/**
+ * passes through all trees by the InOrder crawl type
+ */
+fun , V, Subtree: AbstractBST> traverseInOrderTree(tree: Subtree): List {
+ val treeList = mutableListOf()
+
+ fun recursionAdding(givenTree: Subtree?) {
+ if (givenTree == null) return
+ recursionAdding(givenTree.left)
+ treeList.add(givenTree)
+ recursionAdding(givenTree.right)
+ }
+
+ recursionAdding(tree)
+
+ return treeList
+}
diff --git a/src/test/kotlin/trees/rbtree/rbtreeTest.kt b/src/test/kotlin/trees/rbtree/rbtreeTest.kt
new file mode 100644
index 0000000..5ded2e5
--- /dev/null
+++ b/src/test/kotlin/trees/rbtree/rbtreeTest.kt
@@ -0,0 +1,166 @@
+package trees.rbtree
+
+import org.junit.jupiter.api.Assertions.*
+import org.junit.jupiter.api.BeforeEach
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.TestInstance
+import org.junit.jupiter.params.ParameterizedTest
+import org.junit.jupiter.params.provider.MethodSource
+import trees.correctReferencesParents
+import trees.treeKeysCorrectOrder
+import java.util.*
+import java.util.stream.Stream
+import kotlin.collections.HashMap
+import kotlin.random.Random
+import kotlin.reflect.jvm.internal.impl.resolve.scopes.GivenFunctionsMemberScope
+
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class RedBlackTreeTest {
+
+ private fun , V> checkRBTInvariant(tree: RedBlackTree): Boolean {
+ /**
+ checking that the sons of the red vertex are black
+ */
+ fun checkSonsRedTree(givenTree: RedBlackTree): Boolean {
+ return if (givenTree.color == RedBlackTree.Color.RED) ((givenTree.left?.color
+ ?: RedBlackTree.Color.BLACK) == RedBlackTree.Color.BLACK &&
+ (givenTree.right?.color ?: RedBlackTree.Color.BLACK) == RedBlackTree.Color.BLACK)
+ else true
+ }
+
+ /**
+ * checking that the root of the tree is always black
+ */
+ fun rootIsBlack(givenTree: RedBlackTree): Boolean {
+ return givenTree.color == RedBlackTree.Color.BLACK
+ }
+
+ val blackHeights = HashMap, Int>()
+
+ /**
+ * checking that each tree has the same black depth
+ */
+ fun checkBlackHeightsTrees(givenTree: RedBlackTree?): Boolean {
+ if (givenTree == null) return true
+ val leftBooleanResult = checkBlackHeightsTrees(givenTree.left)
+ val leftBlackHeight = blackHeights[givenTree.left] ?: 1
+ val rightBooleanResult = checkBlackHeightsTrees(givenTree.right)
+ val rightBlackHeight = blackHeights[givenTree.right] ?: 1
+ blackHeights[givenTree] =
+ if (givenTree.color == RedBlackTree.Color.BLACK) leftBlackHeight + 1 else leftBlackHeight
+
+ return leftBooleanResult && rightBooleanResult && (leftBlackHeight == rightBlackHeight) && checkSonsRedTree(
+ givenTree)
+ }
+
+ return correctReferencesParents(tree.root) && treeKeysCorrectOrder(tree.root) && rootIsBlack(tree.root)
+ && checkBlackHeightsTrees(tree.root)
+ }
+
+
+ private val randomizer = Random(87)
+ private val keys = Array(1000) { randomizer.nextInt() }.distinct()
+ private val values = Array(keys.size) { randomizer.nextInt() }.distinct()
+ private lateinit var tree: RedBlackTree
+
+ @BeforeEach
+ fun recreateTree() {
+ tree = RedBlackTree()
+ }
+
+ private fun getData() = Stream.of(
+ Pair(10, 68),
+ Pair(10, 89),
+ Pair(1000, 211),
+ Pair(1000, 42),
+ Pair(100000, 20),
+ Pair(100000, 1337)
+ )
+
+ @ParameterizedTest
+ @MethodSource("getData")
+ fun `insert, remove and find values`(currentData: Pair) {
+ val arraySize = currentData.first
+ val seed = currentData.second
+
+ val currentRandomizer = Random(seed)
+ val keys = List(arraySize) { currentRandomizer.nextInt() }.distinct()
+ val values = List(keys.size) { currentRandomizer.nextInt() }
+ val map = mutableMapOf()
+ for (i in keys.indices) {
+ map[keys[i]] = values[i]
+ }
+
+ for (key in map.keys) {
+ tree.insert(key)
+ }
+ assertTrue(checkRBTInvariant(tree))
+ for (key in map.keys.shuffled()) {
+ tree.remove(key)
+ assertNull(tree.findByKey(key))
+ }
+ assertTrue(checkRBTInvariant(tree))
+ }
+
+ @Test
+ fun `invariant and find after deletion`() {
+ for (i in keys.indices) tree.insert(keys[i], values[i])
+ val leftRange = (Math.random() * keys.size).toInt()
+ val rightRange = (Math.random() * (keys.size - leftRange + 1)).toInt() + leftRange
+ for (i in leftRange until rightRange) {
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ tree.remove(keys[i])
+ assertTrue(checkRBTInvariant(tree))
+ assertNull(tree.findByKey(keys[i]))
+ }
+ }
+
+ @Test
+ fun `invariant and find after insertion`() {
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ assertTrue(checkRBTInvariant(tree))
+ }
+ }
+
+ @Test
+ fun `invariant after insertion duplicates`() {
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkRBTInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ val values = Array(keys.size) { randomizer.nextInt() }
+ for (i in keys.indices) {
+ tree.insert(keys[i], values[i])
+ assertTrue(checkRBTInvariant(tree))
+ assertEquals(tree.findByKey(keys[i]), values[i])
+ }
+ }
+
+ @Test
+ fun `find by non-existent key and return null`() {
+ tree.insert(10)
+ assertNull(tree.findByKey(5))
+ assertNull(tree.findByKey(100))
+ }
+
+ @Test
+ fun `overwriting the key value`() {
+ tree.insert(10, 10)
+ assertEquals(tree.value, 10)
+ tree.insert(10, 20)
+ assertEquals(tree.value, 20)
+ }
+
+ @Test
+ fun `removing a non-existent key`() {
+ val keys = listOf(10, 20, 30)
+ keys.forEach { tree.insert(it, it) }
+ val deletedKeys = listOf(2, 40, 25)
+ deletedKeys.forEach { tree.remove(it) }
+ keys.forEach { assertEquals(tree.findByKey(it), it) }
+ deletedKeys.forEach { assertNull(tree.findByKey(it)) }
+ }
+}
\ No newline at end of file