diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.github/mergeable.yml b/.github/mergeable.yml new file mode 100644 index 0000000..c042f8e --- /dev/null +++ b/.github/mergeable.yml @@ -0,0 +1,14 @@ +version: 2 +mergeable: + - when: pull_request.*, pull_request_review.* + validate: + - do: description + no_empty: + enabled: true + message: "Description should not be empty." + + - do: approvals + min: + count: 1 + required: + assignees: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..9e7ba22 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,39 @@ +## Title (hint) + +Describe what you've changed or added in terms of functionality. + +For example: + +> Added the `update` function to RBTree + +> Fixed an error updating the left subtree + +## Description + +Fixes ... + +Add more info _if needed_: +* context/purpose for implementing changes +* detailed description of the changes made + +## How to test + +### Automated tests + +Please specify the _automated tests_ for your code changes: you should either mention the existing tests or add the new ones. + +### Manual tests + +If it is impossible to provide the automated tests, please reason why. Usually, it is relevant only for UI- or documentation-related PRs. +If this is your case, share the detailed _manual scenarios_ that help to verify your changes. + +## Self-check list + +Check off the item if the statement is true. Hint: [x] is a marked item. + +Please do not delete the list or its items. + +- [ ] PR **title** and **description** are clear and intelligible. +- [ ] I've added enough **comments** to my code, particularly in hard-to-understand areas. +- [ ] The functionality I've repaired, changed or added is covered with **automated tests**. +- [ ] **Manual tests** have been provided optionally. diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml new file mode 100644 index 0000000..a024294 --- /dev/null +++ b/.github/workflows/CI.yml @@ -0,0 +1,45 @@ +name: Run build project + +on: + push: +jobs: + build-gradle-project: + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + + steps: + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: zulu + + - name: Checkout project sources + uses: actions/checkout@v3 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2 + + - name: Run build with Gradle Wrapper + run: ./gradlew build + + - name: Upload lib jar + uses: actions/upload-artifact@v3 + if: github.ref == 'refs/heads/main' + with: + name: BSTrees lib + path: lib/build/libs/lib.jar + + - 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: lib/build/jacoco/jacocoCsv \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1363458 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Gradle # +.gradle + +# Compiled Class Files # +build/ +.idea +*.class + +# Log Files # +*.log + +# Package Files # +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar +*.jar +!gradle-wrapper.jar + +# Out Package # +/out/ + +# MacOS # +*.DS_Store +.AppleDouble + +# db files +*.json +*/SQLTrees diff --git a/CONTAINER.conf b/CONTAINER.conf new file mode 100644 index 0000000..6c88181 --- /dev/null +++ b/CONTAINER.conf @@ -0,0 +1,3 @@ +CONTAINER_NAME=neo4j-db +PASSWORD="qwertyui" +EXAMPLE_DIR="/example" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. \ No newline at end of file diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..3781a1f --- /dev/null +++ b/NOTICE @@ -0,0 +1,2 @@ +Trees-6 +Copyright 2023 Kirill Shishin, Leonid Elkin, Rostislav Borisov \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8711ffd --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# trees-6 +`BSTrees` is a library that allows you to use 3 types of binary search trees: randomized BSTree, AVLTree, RBTree. + +## How to use + +To build the library run +```bash + ./gradlew build +``` + To create each of the tree views, you can use: + ```kotlin +val rbTree = RBTree() // instantiate empty red-black tree +val avlTree = AvlTree() // instantiate empty AVL tree +val bsTree = BSTree() // instantiate empty simple tree +``` +The first type parameter is a comparable key. \ +The second type parameter is a stored value. It can be anything + +Each tree supports 3 basic operations: `insert`, `find`, `delete`. + ```kotlin +val bsTree = BSTree() + +bsTree.insert("bruh", 5) +bsTree.find("bruh") // 5 +bsTree.delete("bruh") +``` + +## Storing BSTs +You can store any tree in any of the three databases presented. These are `Neo4j`, `SQLite` and `Json`. You can choose the types of key and value on wich the tree is built, but supported only string and int if you want to store it + +To use `Neo4j`, you need to install the desktop application `Doсker`, open it and perform `neo4j_up.sh` with with the necessary configurations, which are in the `CONTAINER.conf` file + +# User Interface + +You can interact with the trees directly using the provided user interface. It allows you to choose the database, the types of keys and values on which the tree is built, as well as save and unload trees from databases. Again, you can create and load any trees to any data bases. + + + +## License +Distributed under the Apache 2.0 License. See [LICENSE](https://github.com/spbu-coding-2022/trees-6/blob/main/LICENSE) for more information. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..9fdfdd1 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,28 @@ +val composeVersion: String? by rootProject + +plugins { + id("org.jetbrains.kotlin.jvm") version "1.8.20" + id("org.jetbrains.compose") version "1.4.0" + + application +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(project(":lib")) + + implementation("com.arkivanov.decompose:extensions-compose-jetbrains:$composeVersion") + implementation("com.arkivanov.decompose:decompose:$composeVersion") + + implementation(compose.desktop.currentOs) + implementation(compose.material3) +} + + +application { + // Define the main class for the application. + mainClass.set("app/view/AppKt") +} diff --git a/app/src/main/kotlin/app/presenter/DataBasePresenter.kt b/app/src/main/kotlin/app/presenter/DataBasePresenter.kt new file mode 100644 index 0000000..36ef6d5 --- /dev/null +++ b/app/src/main/kotlin/app/presenter/DataBasePresenter.kt @@ -0,0 +1,19 @@ +package app.presenter + +import bstrees.model.dataBases.reps.JsonTreeRepo +import bstrees.model.dataBases.reps.Neo4jTreeRepo +import bstrees.model.dataBases.reps.SQLTreeRepo + +object DataBasePresenter { + fun connectNeo4j(host: String, username: String, password: String): TreePresenter { + return TreePresenter(Neo4jTreeRepo(host, username, password)) + } + + fun connectSQL(bdName: String): TreePresenter { + return TreePresenter(SQLTreeRepo(bdName)) + } + + fun connectJson(dirName: String): TreePresenter { + return TreePresenter(JsonTreeRepo(dirName)) + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/presenter/LayoutPresenter.kt b/app/src/main/kotlin/app/presenter/LayoutPresenter.kt new file mode 100644 index 0000000..e6acfad --- /dev/null +++ b/app/src/main/kotlin/app/presenter/LayoutPresenter.kt @@ -0,0 +1,53 @@ +package app.presenter + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import app.presenter.utils.TreeHeightPresenter +import kotlin.math.pow + +object LayoutPresenter { + + private const val windowHeight = 800 + private const val windowWidth = 800 + private var edgeLengthY = 10 + + + fun getNodeSize(tree: TreeData): Int{ + val treeHeight = TreeHeightPresenter.getTreeHeight(tree) + return windowHeight / 5 / (treeHeight + 1) + } + + fun setTreeLayout(tree: TreeData){ + + val treeHeight = TreeHeightPresenter.getTreeHeight(tree) + + edgeLengthY = windowHeight / (treeHeight + 1) + + tree.root?.let {root-> + root.posX = 800 + root.posY = 0 + + setNodesLayout(root, 0) + } + + } + + // This method will assign coordinates to the nodes of the tree + private fun setNodesLayout(node: NodeData, height: Int){ + val edgeLengthX = windowWidth / 2.0.pow(height + 1).toInt() + + node.leftNode?.let {leftNode-> + leftNode.posX = node.posX - edgeLengthX + leftNode.posY = node.posY + edgeLengthY + + setNodesLayout(leftNode, height + 1) + } + + node.rightNode?.let { rightNode -> + rightNode.posX = node.posX + edgeLengthX + rightNode.posY = node.posY + edgeLengthY + + setNodesLayout(rightNode, height + 1) + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/presenter/TreePresenter.kt b/app/src/main/kotlin/app/presenter/TreePresenter.kt new file mode 100644 index 0000000..a091b45 --- /dev/null +++ b/app/src/main/kotlin/app/presenter/TreePresenter.kt @@ -0,0 +1,76 @@ +package app.presenter + +import bstrees.model.dataBases.reps.TreeRepo +import bstrees.model.dataBases.TreeData +import bstrees.model.dataBases.converters.TreeToDataConverter +import bstrees.model.dataBases.converters.treesConverters.AvlToDataConverter +import bstrees.model.dataBases.converters.treesConverters.RandomBsToDataConverter +import bstrees.model.dataBases.converters.treesConverters.RbToDataConverter +import bstrees.model.dataBases.converters.utils.createStringConverter +import bstrees.model.trees.BSTree + + +class TreePresenter(private val db: TreeRepo) { + lateinit var tree: TreeData + private set + + fun loadTree(treeName: String, treeType: String) { + tree = db.getTree(treeName, treeType) ?: throw IllegalArgumentException("There is no tree with that name: $treeName") + } + + fun saveTree(){ + db.setTree(tree) + } + + fun createTree(treeName: String, treeType: String, keyType: String, valueType: String) { + tree = TreeData(treeName, treeType, keyType, valueType, null) + db.setTree(tree) + } + + private fun createStrategy(): TreeToDataConverter<*, *, *, *, *> = when (tree.treeType) { + "AVL" -> AvlToDataConverter( + keyStringConverter = createStringConverter(tree.keyType), + valueStringConverter = createStringConverter(tree.valueType), + keyType = tree.keyType, + valueType = tree.valueType + ) + "RB" -> RbToDataConverter( + keyStringConverter = createStringConverter(tree.keyType), + valueStringConverter = createStringConverter(tree.valueType), + keyType = tree.keyType, + valueType = tree.valueType + ) + "BS" -> RandomBsToDataConverter( + keyStringConverter = createStringConverter(tree.keyType), + valueStringConverter = createStringConverter(tree.valueType), + keyType = tree.keyType, + valueType = tree.valueType + ) + else -> throw IllegalArgumentException("Unknown tree type ${tree.treeType}") + } + + + fun addNode(key: String, value: String) { + fun , V, TREE_TYPE : BSTree> helper(strategy: TreeToDataConverter) { + val bTree = strategy.deserializeTree(tree) + bTree.insert( + strategy.keyStringConverter.fromString(key), + strategy.valueStringConverter.fromString(value) + ) + tree = strategy.serializeTree(bTree, tree.name) + } + helper(createStrategy()) + } + + + fun deleteNode(key: String) { + fun , V, TREE_TYPE : BSTree> helper(strategy: TreeToDataConverter) { + val bTree = strategy.deserializeTree(tree) + bTree.delete( + strategy.keyStringConverter.fromString(key), + ) + tree = strategy.serializeTree(bTree, tree.name) + } + helper(createStrategy()) + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/presenter/utils/TreeHeightPresenter.kt b/app/src/main/kotlin/app/presenter/utils/TreeHeightPresenter.kt new file mode 100644 index 0000000..5c71dcb --- /dev/null +++ b/app/src/main/kotlin/app/presenter/utils/TreeHeightPresenter.kt @@ -0,0 +1,15 @@ +package app.presenter.utils + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import java.lang.Integer.max + +object TreeHeightPresenter { + + fun getTreeHeight(tree: TreeData): Int = getNodeHeight(tree.root) + + private fun getNodeHeight(node: NodeData?): Int { + return node?.let { 1 + max(getNodeHeight(node.leftNode), getNodeHeight(node.rightNode)) } ?: 0 + } + +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/App.kt b/app/src/main/kotlin/app/view/App.kt new file mode 100644 index 0000000..9aa71fc --- /dev/null +++ b/app/src/main/kotlin/app/view/App.kt @@ -0,0 +1,193 @@ +package app.view + +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.window.* +import app.presenter.DataBasePresenter +import app.presenter.TreePresenter +import app.view.assets.ChildStack +import app.view.utils.Databases +import app.view.assets.ProvideComponentContext +import app.view.screens.TreeView +import app.view.screens.* +import com.arkivanov.decompose.DefaultComponentContext +import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.fade +import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.plus +import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.scale +import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.stackAnimation +import com.arkivanov.decompose.router.stack.StackNavigation +import com.arkivanov.decompose.router.stack.pop +import com.arkivanov.decompose.router.stack.push +import com.arkivanov.essenty.lifecycle.LifecycleRegistry +import java.awt.Dimension + +fun main() { + + val lifecycle = LifecycleRegistry() + val rootComponentContext = DefaultComponentContext(lifecycle = lifecycle) + + application { + Window( + onCloseRequest = ::exitApplication, + title = "graph", + state = rememberWindowState( + position = WindowPosition(alignment = Alignment.Center), + ), + + ) { + window.minimumSize = Dimension(800, 800) + window.maximumSize = Dimension(800, 800) + + ProvideComponentContext(rootComponentContext) { + + val databaseChoice = remember { mutableStateOf("▾") } + val databaseMetadata = remember { mutableStateOf("") } + val username = remember { mutableStateOf("") } + val password = remember { mutableStateOf("") } + val navigation = remember { StackNavigation() } + val treeType = remember { mutableStateOf("▾") } + val treeName = remember { mutableStateOf("") } + val keyType = remember { mutableStateOf("▾") } + val valueType = remember { mutableStateOf("▾") } + var isDirectoryNameWritten = true + var treePresenter: TreePresenter? = null + val isUpdatedTree = remember { mutableStateOf(false) } + + // for tree adding and deleting + val key = remember { mutableStateOf("Enter key") } + val value = remember { mutableStateOf("Enter value") } + + ChildStack( + source = navigation, + initialStack = { listOf(ScreenManager.HomeScreen) }, + handleBackButton = true, + animation = stackAnimation(fade() + scale()), + ) { screen -> + when (screen) { + + is ScreenManager.HomeScreen -> { + + HomeScreen( + databaseChoice, + { newHeader -> databaseChoice.value = newHeader }, + databaseMetadata, + username, + password, + { newMeta -> + databaseMetadata.value = + if ( + databaseMetadata.value == "" && + databaseChoice.value == Databases.Json.toString() && + !isDirectoryNameWritten + ) + "jsondir" + else newMeta + }, + { newUsername -> username.value = newUsername }, + { newPassword -> password.value = newPassword }, + { + if (databaseMetadata.value == "") isDirectoryNameWritten = false + navigation.push(ScreenManager.TreeChoosingScreen) + } + ) + + } + + is ScreenManager.TreeChoosingScreen -> { + + treePresenter = when (databaseChoice.value) { + + Databases.Neo4j.toString() -> DataBasePresenter.connectNeo4j( + databaseMetadata.value, + username.value, + password.value + ) + + Databases.Json.toString() -> DataBasePresenter.connectJson(databaseMetadata.value) + + Databases.SQLite.toString() -> DataBasePresenter.connectSQL(databaseMetadata.value) + + else -> throw Exception("Incorrect database") + + } + + treePresenter?.let { treePresenter -> + TreeChoosingScreen( + treeType, + { newHeader -> treeType.value = newHeader }, + treePresenter, + treeName = treeName, + { newName -> treeName.value = newName }, + back = navigation::pop, + { navigation.push(ScreenManager.TypesChoosingScreen) }, + { navigation.push(ScreenManager.TreeScreen) }, + { newValue -> isUpdatedTree.value = newValue} + ) + } + + } + + is ScreenManager.TypesChoosingScreen -> { + treePresenter?.let { treePresenter -> + TypesChoosingScreen( + treePresenter, + treeName, + treeType, + keyType, + valueType, + { newKeyType -> keyType.value = newKeyType }, + { newValueType -> valueType.value = newValueType }, + back = navigation::pop, + approve = { navigation.push(ScreenManager.TreeScreen) } + ) + } + } + + is ScreenManager.TreeScreen -> { + + + treePresenter?.let { treePresenter -> + TreeView( + treePresenter, + addNode = { navigation.push(ScreenManager.AddNodeScreen) }, + deleteNode = { navigation.push(ScreenManager.DeleteNodeScreen) }, + isUpdatedTree, + { newValue -> isUpdatedTree.value = newValue} + ) + } + } + + is ScreenManager.AddNodeScreen -> { + key.value = "Enter key" + value.value = "Enter value" + treePresenter?.let { treePresenter -> + AddNodeScreen( + treePresenter, + key, + value, + { newKey -> key.value = newKey }, + { newValue -> value.value = newValue }, + back = { navigation.pop() }, + approve = { navigation.pop() } + ) + } + } + + is ScreenManager.DeleteNodeScreen -> { + key.value = "Enter key" + treePresenter?.let { treePresenter -> + DeleteNodeScreen( + treePresenter, + key, + { newKey -> key.value = newKey }, + back = { navigation.pop() }, + approve = { navigation.pop() } + ) + } + } + } + } + } + } + } +} diff --git a/app/src/main/kotlin/app/view/assets/DatabaseConnections.kt b/app/src/main/kotlin/app/view/assets/DatabaseConnections.kt new file mode 100644 index 0000000..6c9469c --- /dev/null +++ b/app/src/main/kotlin/app/view/assets/DatabaseConnections.kt @@ -0,0 +1,116 @@ +package app.view.assets + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.* +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp + +@Composable +fun databaseConnectionJson( + directory: State, + hostChange: (String) -> Unit, + approveChange: () -> Unit +) { + Column(modifier = Modifier.padding(vertical = 16.dp)) { + + OutlinedTextField( + value = directory.value, + onValueChange = hostChange, + label = { Text("Enter the directory name") }, + placeholder = { Text("jsondir") } + ) + + Spacer(modifier = Modifier.height(15.dp)) + + Button(onClick = approveChange) { + Text("Approve") + } + } +} + +@Composable +fun databaseConnectionSQL( + name: State, + hostChange: (String) -> Unit, + approveChange: () -> Unit +) { + Column(modifier = Modifier.padding(vertical = 16.dp)) { + + OutlinedTextField( + value = name.value, + onValueChange = hostChange, + label = { Text("Enter the database name") }, + colors = TextFieldDefaults.textFieldColors( + textColor = if (name.value == "Enter the database name") Color.Gray else Color.Black, + backgroundColor = Color.White, + ) + ) + + Spacer(modifier = Modifier.height(15.dp)) + + Button(onClick = approveChange) { + Text("Approve") + } + } +} + +@Composable +fun databaseConnectionNeo4j( + databaseMetadata: State, + username: State, + password: State, + hostChange: (String) -> Unit, + usernameChange: (String) -> Unit, + passwordChange: (String) -> Unit, + approveChange: () -> Unit +) { + Column(modifier = Modifier.padding(vertical = 16.dp)) { + + OutlinedTextField( + value = databaseMetadata.value, + onValueChange = hostChange, + label = { Text("Enter host") }, + colors = TextFieldDefaults.textFieldColors( + textColor = if (databaseMetadata.value == "Enter host") Color.Gray else Color.Black, + backgroundColor = Color.White, + ) + ) + + Spacer(modifier = Modifier.height(10.dp)) + + OutlinedTextField( + value = username.value, + onValueChange = usernameChange, + label = { Text("Enter username") }, + colors = TextFieldDefaults.textFieldColors( + textColor = if (username.value == "Enter username") Color.Gray else Color.Black, + backgroundColor = Color.White, + ) + ) + + Spacer(modifier = Modifier.height(10.dp)) + + OutlinedTextField( + value = password.value, + onValueChange = passwordChange, + label = { Text("Enter password") }, + colors = TextFieldDefaults.textFieldColors( + textColor = if (password.value == "Enter password") Color.Gray else Color.Black, + backgroundColor = Color.White, + ) + ) + + Spacer(modifier = Modifier.height(15.dp)) + + Button(onClick = approveChange) { + Text("Approve") + } + + } +} diff --git a/app/src/main/kotlin/app/view/assets/Navigation.kt b/app/src/main/kotlin/app/view/assets/Navigation.kt new file mode 100644 index 0000000..ddf96cd --- /dev/null +++ b/app/src/main/kotlin/app/view/assets/Navigation.kt @@ -0,0 +1,47 @@ +package app.view.assets + +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import com.arkivanov.decompose.ComponentContext +import com.arkivanov.decompose.extensions.compose.jetbrains.stack.Children +import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.StackAnimation +import com.arkivanov.decompose.router.stack.StackNavigationSource +import com.arkivanov.decompose.router.stack.childStack +import com.arkivanov.essenty.parcelable.Parcelable + +val LocalComponentContext: ProvidableCompositionLocal = + staticCompositionLocalOf { error("Root component context was not provided") } + +@Composable +fun ProvideComponentContext(componentContext: ComponentContext, content: @Composable () -> Unit) { + CompositionLocalProvider(LocalComponentContext provides componentContext, content = content) +} + +@Composable +inline fun ChildStack( + source: StackNavigationSource, + noinline initialStack: () -> List, + modifier: Modifier = Modifier, + handleBackButton: Boolean = false, + animation: StackAnimation? = null, + noinline content: @Composable (C) -> Unit, +) { + val componentContext = LocalComponentContext.current + + Children( + stack = remember { + componentContext.childStack( + source = source, + initialStack = initialStack, + handleBackButton = handleBackButton, + childFactory = { _, childComponentContext -> childComponentContext }, + ) + }, + modifier = modifier, + animation = animation, + ) { child -> + ProvideComponentContext(child.instance) { + content(child.configuration) + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/assets/Selector.kt b/app/src/main/kotlin/app/view/assets/Selector.kt new file mode 100644 index 0000000..d4e2cd6 --- /dev/null +++ b/app/src/main/kotlin/app/view/assets/Selector.kt @@ -0,0 +1,59 @@ +package app.view.assets + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape +import androidx.compose.material.DropdownMenu +import androidx.compose.material.DropdownMenuItem +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +@Composable +fun Selector(header: State, onClickChanges: (String) -> Unit, items: List) { + var expanded by remember { mutableStateOf(false) } + var selectedIndex by remember { mutableStateOf(0) } + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + + Row( + horizontalArrangement = if (header.value != "▾") Arrangement.Center else Arrangement.End, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .clickable(onClick = { expanded = true }) + .background(Color.White) + .border(width = 1.dp, shape = AbsoluteRoundedCornerShape(10.dp), color = Color.Blue) + .width(300.dp) + .height(40.dp) + .absoluteOffset(if (header.value == "▾") -12.dp else 0.dp) + ) { + Text( + header.value, + fontSize = 25.sp, + ) + } + + DropdownMenu( + expanded = expanded, + onDismissRequest = { expanded = false }, + modifier = Modifier + .fillMaxWidth() + .background(Color.White) + ) { + items.forEachIndexed { index, s -> + DropdownMenuItem(onClick = { + selectedIndex = index + onClickChanges(items[selectedIndex]) + expanded = false + }) { + Text(text = s) + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/screens/AddNodeScreen.kt b/app/src/main/kotlin/app/view/screens/AddNodeScreen.kt new file mode 100644 index 0000000..e2b12d5 --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/AddNodeScreen.kt @@ -0,0 +1,53 @@ +package app.view.screens + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.Button +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import app.presenter.TreePresenter +import app.view.assets.Selector + +@Composable +fun AddNodeScreen( + treePresenter: TreePresenter, + key: State, + value: State, + ChangesKey: (String) -> Unit, + ChangesValue: (String) -> Unit, + back: () -> Unit, + approve: () -> Unit +) { + Column(modifier = Modifier.padding(16.dp)) { + + OutlinedTextField(value = key.value, onValueChange = ChangesKey) + + Spacer(modifier = Modifier.height(16.dp)) + + OutlinedTextField(value = value.value, onValueChange = ChangesValue) + + Spacer(modifier = Modifier.height(16.dp)) + + if ( + key.value != "Enter key" && + value.value != "Enter value" + ) { + Button(onClick = { + treePresenter.addNode(key.value, value.value) + approve() + }) { + Text("add node") + } + } + + Button(onClick = back) { + Text("back") + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/screens/DeleteNodeScreen.kt b/app/src/main/kotlin/app/view/screens/DeleteNodeScreen.kt new file mode 100644 index 0000000..8898f44 --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/DeleteNodeScreen.kt @@ -0,0 +1,46 @@ +package app.view.screens + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.Button +import androidx.compose.material.OutlinedTextField +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import app.presenter.TreePresenter +import app.view.assets.Selector + +@Composable +fun DeleteNodeScreen( + treePresenter: TreePresenter, + key: State, + ChangesKey: (String) -> Unit, + back: () -> Unit, + approve: () -> Unit +) { + Column(modifier = Modifier.padding(16.dp)) { + + OutlinedTextField(value = key.value, onValueChange = ChangesKey) + + Spacer(modifier = Modifier.height(16.dp)) + + if ( + key.value != "Enter key" + ) { + Button(onClick = { + treePresenter.deleteNode(key.value) + approve() + }) { + Text("delete node") + } + } + + Button(onClick = back) { + Text("back") + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/screens/HomeScreen.kt b/app/src/main/kotlin/app/view/screens/HomeScreen.kt new file mode 100644 index 0000000..270852d --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/HomeScreen.kt @@ -0,0 +1,63 @@ +package app.view.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import app.view.assets.* +import app.view.utils.Databases + +@Composable +fun HomeScreen( + databaseName: State, + onClickChanges: (String) -> Unit, + host: State, + username: State, + password: State, + hostChange: (String) -> Unit, + usernameChange: (String) -> Unit, + passwordChange: (String) -> Unit, + approveChange: () -> Unit +) { + Column(modifier = Modifier.padding(16.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Choose your database:") + Spacer(modifier = Modifier.width(10.dp)) + Selector( + databaseName, + onClickChanges, + listOf(Databases.Neo4j.toString(), Databases.Json.toString(), Databases.SQLite.toString()) + ) + } + + when (databaseName.value) { + + Databases.Neo4j.toString() -> databaseConnectionNeo4j( + host, + username, + password, + hostChange, + usernameChange, + passwordChange, + approveChange + ) + + Databases.Json.toString() -> databaseConnectionJson( + host, + hostChange, + approveChange + ) + + Databases.SQLite.toString() -> databaseConnectionSQL( + host, + hostChange, + approveChange + ) + } + } +} + + + diff --git a/app/src/main/kotlin/app/view/screens/ScreenManager.kt b/app/src/main/kotlin/app/view/screens/ScreenManager.kt new file mode 100644 index 0000000..360d4d1 --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/ScreenManager.kt @@ -0,0 +1,25 @@ +package app.view.screens + +import com.arkivanov.essenty.parcelable.Parcelable +import com.arkivanov.essenty.parcelable.Parcelize + +sealed class ScreenManager : Parcelable { + + @Parcelize + object HomeScreen : ScreenManager() + + @Parcelize + object TreeChoosingScreen : ScreenManager() + + @Parcelize + object TypesChoosingScreen: ScreenManager() + + @Parcelize + object TreeScreen: ScreenManager() + + @Parcelize + object AddNodeScreen: ScreenManager() + + @Parcelize + object DeleteNodeScreen: ScreenManager() +} diff --git a/app/src/main/kotlin/app/view/screens/TreeChosingScreen.kt b/app/src/main/kotlin/app/view/screens/TreeChosingScreen.kt new file mode 100644 index 0000000..2a943b3 --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/TreeChosingScreen.kt @@ -0,0 +1,85 @@ +package app.view.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import app.presenter.TreePresenter +import app.view.assets.Selector +import app.view.utils.Trees + +@Composable +fun TreeActions( + treePresenter: TreePresenter, + treeName: State, + treeType: State, + createTreeMenu: () -> Unit, + treeView: () -> Unit, +) { + + Column { + + Spacer(modifier = Modifier.height(8.dp)) + + Button( + onClick = { createTreeMenu() }, + modifier = Modifier.width(150.dp) + ) { + Text("Create Tree") + } + + Spacer(modifier = Modifier.height(8.dp)) + + Button( + onClick = { + treePresenter.loadTree(treeName.value, treeType.value) + treeView() + }, + modifier = Modifier.width(150.dp) + ) { + Text("Load Tree") + } + + Spacer(modifier = Modifier.height(8.dp)) + } +} + +@Composable +fun TreeChoosingScreen( + treeType: State, + onClickChanges: (String) -> Unit, + treePresenter: TreePresenter, + treeName: State, + treeNameChange: (String) -> Unit, + back: () -> Unit, + createTreeMenu: () -> Unit, + treeView: () -> Unit, + isLoadedTreeChange: (Boolean) -> Unit, +) { + Column(modifier = Modifier.padding(16.dp)) { + + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Choose your tree:") + Spacer(modifier = Modifier.width(10.dp)) + Selector(treeType, onClickChanges, listOf(Trees.BS.toString(), Trees.RB.toString(), Trees.AVL.toString())) + } + + if (treeType.value != "▾") { + Spacer(modifier = Modifier.height(16.dp)) + OutlinedTextField( + value = treeName.value, + onValueChange = treeNameChange, + label = { Text("Enter the tree name") }, + ) + Spacer(modifier = Modifier.height(8.dp)) + TreeActions(treePresenter, treeName, treeType, createTreeMenu, treeView) + isLoadedTreeChange(false) + } + + Button(onClick = back, modifier = Modifier.width(150.dp)) { + Text("Back") + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/screens/TreeScreen.kt b/app/src/main/kotlin/app/view/screens/TreeScreen.kt new file mode 100644 index 0000000..258f41b --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/TreeScreen.kt @@ -0,0 +1,83 @@ +package app.view.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.material.Button +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import app.presenter.LayoutPresenter +import app.presenter.TreePresenter +import app.view.treeView.Tree + +const val WINDOW_SIZE = 800 + +var nodeSize = 30 + +@Composable +fun TreeActionButtons( + treePresenter: TreePresenter, + addNode: () -> Unit, + deleteNode: () -> Unit, +) { + + Row(modifier = Modifier.background(Color.Cyan).fillMaxWidth(), horizontalArrangement = Arrangement.Center) { + Button(onClick = { + addNode() + }) { + Text("Add Node") + } + + Spacer(modifier = Modifier.width(nodeSize.dp)) + + Button(onClick = + { + deleteNode() + }){ + Text(text = "Delete Node") + } + + Spacer(modifier = Modifier.width(nodeSize.dp)) + + Button(onClick = { + treePresenter.saveTree() + }) { + Text(text = "Save tree") + } + } +} + +@Composable +fun TreeView( + treePresenter: TreePresenter, + addNode: () -> Unit, + deleteNode: () -> Unit, + isUpdatedTree: State, + isUpdatedTreeChanges: (Boolean) -> Unit, +) { + + Column { + val tree = treePresenter.tree + if(isUpdatedTree.value){ + LayoutPresenter.setTreeLayout(tree) + } + else{ + isUpdatedTreeChanges(true) + } + TreeActionButtons(treePresenter, addNode, deleteNode) + nodeSize = LayoutPresenter.getNodeSize(tree) + Box( + modifier = Modifier.height(WINDOW_SIZE.dp).width(WINDOW_SIZE.dp), + ) { + + tree.root?.let { root -> + Tree( + mutableStateOf(root) + ) + } + } + } +} + diff --git a/app/src/main/kotlin/app/view/screens/TypesChoosingScreen.kt b/app/src/main/kotlin/app/view/screens/TypesChoosingScreen.kt new file mode 100644 index 0000000..6399609 --- /dev/null +++ b/app/src/main/kotlin/app/view/screens/TypesChoosingScreen.kt @@ -0,0 +1,69 @@ +package app.view.screens + +import androidx.compose.foundation.layout.* +import androidx.compose.material.Button +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import app.presenter.TreePresenter +import app.view.assets.Selector + +@Composable +fun TypesChoosingScreen( + treePresenter: TreePresenter, + treeName: State, + treeType: State, + keyType: State, + valueType: State, + onClickChangesKey: (String) -> Unit, + onClickChangesValue: (String) -> Unit, + back: () -> Unit, + approve: () -> Unit +) { + Column(modifier = Modifier.padding(16.dp)) { + + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Choose the key type from the following options:") + Spacer(modifier = Modifier.width(10.dp)) + Selector( + keyType, + onClickChangesKey, + listOf("Int", "String") + ) + } + + + Spacer(modifier = Modifier.height(16.dp)) + + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Choose the value type from the following options:") + Spacer(modifier = Modifier.width(10.dp)) + Selector( + valueType, + onClickChangesValue, + listOf("Int", "String") + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + if ( + keyType.value != "▾" && + valueType.value != "▾" + ) { + Button(onClick = { + treePresenter.createTree(treeName.value, treeType.value, keyType.value, valueType.value) + approve() + }) { + Text("Approve and create") + } + } + + Button(onClick = back) { + Text("back") + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/treeView/Edge.kt b/app/src/main/kotlin/app/view/treeView/Edge.kt new file mode 100644 index 0000000..477ce60 --- /dev/null +++ b/app/src/main/kotlin/app/view/treeView/Edge.kt @@ -0,0 +1,32 @@ +package app.view.treeView + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import app.view.screens.nodeSize +import app.view.screens.WINDOW_SIZE +import bstrees.model.dataBases.NodeData + +@Composable +fun Edge( + node1: State, + node2: State, + modifier: Modifier = Modifier +) { + Canvas( + modifier = modifier.size(WINDOW_SIZE.dp), + onDraw = { + drawLine( + start = Offset(x = node1.value.posX.toFloat() + nodeSize, y = node1.value.posY.toFloat() + nodeSize), + end = Offset(x = node2.value.posX.toFloat() + nodeSize, y = node2.value.posY.toFloat() + nodeSize), + color = Color.Black, + strokeWidth = 3F + ) + } + ) +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/treeView/Node.kt b/app/src/main/kotlin/app/view/treeView/Node.kt new file mode 100644 index 0000000..6aa874a --- /dev/null +++ b/app/src/main/kotlin/app/view/treeView/Node.kt @@ -0,0 +1,81 @@ +package app.view.treeView + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.State +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChange +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import app.view.screens.nodeSize +import bstrees.model.dataBases.NodeData +import java.lang.Float.max +import java.lang.Float.min + +@Composable +fun Node(node: State, nodeCoords: MutableState>) { + node.value.posX = nodeCoords.value.first.toInt() + node.value.posY = nodeCoords.value.second.toInt() + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .offset { IntOffset(nodeCoords.value.first.toInt(), nodeCoords.value.second.toInt()) } + .background(Color.Red, CircleShape) + .size(nodeSize.dp) + .pointerInput(Unit) { + detectDragGestures { change, dragAmount -> + val newXPos = max(0f, min(1550f, nodeCoords.value.first + dragAmount.x)) + val newYPos = max(0f, min(1400f, nodeCoords.value.second + dragAmount.y)) + + nodeCoords.value = Pair( + newXPos, + newYPos + ) + if (change.positionChange() != Offset.Zero) change.consume() + } + } + .background( + color = if (node.value.metadata == "RED") Color.Red + else if (node.value.metadata == "BLACK") Color.Black + else Color.Magenta, + shape = CircleShape + ) + .width(nodeSize.dp) + .height(nodeSize.dp) + .border( + width = 1.dp, + color = Color.Blue, + shape = CircleShape + ) + + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally + ) { + Text( + text = "Key: ${node.value.key}", + textAlign = TextAlign.Center, + color = Color.White, + fontSize = if (((nodeSize / 4)) > 20) 20.sp else (nodeSize / 4).sp + ) + Text( + text = "Value: ${node.value.value}", + textAlign = TextAlign.Center, + color = Color.White, + fontSize = if (((nodeSize / 4)) > 20) 20.sp else (nodeSize / 4).sp + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/app/view/treeView/Tree.kt b/app/src/main/kotlin/app/view/treeView/Tree.kt new file mode 100644 index 0000000..cc7ebba --- /dev/null +++ b/app/src/main/kotlin/app/view/treeView/Tree.kt @@ -0,0 +1,31 @@ +package app.view.treeView + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import bstrees.model.dataBases.NodeData + +@Composable +fun Tree( + node: State, +) { + + val nodeCoords = remember { mutableStateOf(Pair( + node.value.posX.toFloat(), node.value.posY.toFloat())) } + + node.value.leftNode?.let { leftNode -> + Edge(node, mutableStateOf(leftNode)) + } + node.value.rightNode?.let { rightNode -> + Edge(node, mutableStateOf(rightNode)) + } + node.value.leftNode?.let { leftNode -> + Tree(mutableStateOf(leftNode)) + } + node.value.rightNode?.let { rightNode -> + Tree(mutableStateOf(rightNode)) + } + + Node(node, nodeCoords) +} diff --git a/app/src/main/kotlin/app/view/utils/Databases.kt b/app/src/main/kotlin/app/view/utils/Databases.kt new file mode 100644 index 0000000..a4e301e --- /dev/null +++ b/app/src/main/kotlin/app/view/utils/Databases.kt @@ -0,0 +1,7 @@ +package app.view.utils + +enum class Databases { + Neo4j, + Json, + SQLite +} diff --git a/app/src/main/kotlin/app/view/utils/Trees.kt b/app/src/main/kotlin/app/view/utils/Trees.kt new file mode 100644 index 0000000..86b2985 --- /dev/null +++ b/app/src/main/kotlin/app/view/utils/Trees.kt @@ -0,0 +1,7 @@ +package app.view.utils + +enum class Trees { + RB, + AVL, + BS +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2d52fe7 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +junit5Version=5.9.1 +jetbrainsExposedVersion=0.38.1 +gsonVersion=2.8.5 +kotlinxSerializationVersion=1.5.0 +neo4jDriverVersion=5.6.0 +sqliteJdbcVersion=3.34.0 +kotlinLoggingVersion=2.0.6 +slf4jVersion=1.7.29 +composeVersion=2.0.0-alpha-02 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..ccebba7 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bdc9a83 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..79a61d4 --- /dev/null +++ b/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/build.gradle.kts b/lib/build.gradle.kts new file mode 100644 index 0000000..423e737 --- /dev/null +++ b/lib/build.gradle.kts @@ -0,0 +1,61 @@ +val jetbrainsExposedVersion: String? by rootProject +val junit5Version: String? by rootProject +val gsonVersion: String? by rootProject +val kotlinxSerializationVersion: String? by rootProject +val neo4jDriverVersion: String? by rootProject +val sqliteJdbcVersion: String? by rootProject +val kotlinLoggingVersion: String? by rootProject +val slf4jVersion: String? by rootProject + +plugins { + id("org.jetbrains.kotlin.jvm") version "1.8.20" + kotlin("plugin.serialization") version "1.8.20" + + jacoco + application +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinxSerializationVersion") + + implementation("com.google.code.gson:gson:$gsonVersion") + + implementation("org.neo4j.driver:neo4j-java-driver:$neo4jDriverVersion") + + implementation("org.jetbrains.exposed:exposed-core:$jetbrainsExposedVersion") + implementation("org.jetbrains.exposed:exposed-jdbc:$jetbrainsExposedVersion") + implementation("org.jetbrains.exposed:exposed-dao:$jetbrainsExposedVersion") + implementation("org.xerial:sqlite-jdbc:$sqliteJdbcVersion") + + implementation("io.github.microutils:kotlin-logging-jvm:$kotlinLoggingVersion") + implementation("org.slf4j:slf4j-simple:$slf4jVersion") + + testImplementation("org.junit.jupiter:junit-jupiter-engine:$junit5Version") + testImplementation("org.junit.jupiter:junit-jupiter-params:$junit5Version") +} + +tasks.getByName("test") { + useJUnitPlatform() +} + +tasks.jacocoTestReport { + reports { + csv.required.set(true) + csv.outputLocation.set(layout.buildDirectory.file("jacoco/jacocoCsv")) + } + classDirectories.setFrom( + files(classDirectories.files.map { + fileTree(it) { + include("**/model/**") + exclude("**/**/*Neo4jTreeRepo*.*") + exclude("**/**/*TreeData*.*") + exclude("**/**/*NodeData*.*") + } + }) + ) +} + diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/NodeData.kt b/lib/src/main/kotlin/bstrees/model/dataBases/NodeData.kt new file mode 100644 index 0000000..66c7afe --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/NodeData.kt @@ -0,0 +1,17 @@ +package bstrees.model.dataBases + +import kotlinx.serialization.Serializable + +@Serializable +class NodeData( + val key: String, + val value: String, + val metadata: String, //If RB meta is RED or BLACK in capital letters + + //layout + var posX: Int, + var posY: Int, + + val leftNode: NodeData? = null, + val rightNode: NodeData? = null, +) \ No newline at end of file diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/TreeData.kt b/lib/src/main/kotlin/bstrees/model/dataBases/TreeData.kt new file mode 100644 index 0000000..077ef54 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/TreeData.kt @@ -0,0 +1,12 @@ +package bstrees.model.dataBases + +import kotlinx.serialization.Serializable + +@Serializable +class TreeData( + val name: String, + val treeType: String, //RB, AVL or BS in capital letters!!! + val keyType: String, + val valueType: String, + val root: NodeData?, +) diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/converters/TreeToDataConverter.kt b/lib/src/main/kotlin/bstrees/model/dataBases/converters/TreeToDataConverter.kt new file mode 100644 index 0000000..1fe161f --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/converters/TreeToDataConverter.kt @@ -0,0 +1,28 @@ +package bstrees.model.dataBases.converters + +import bstrees.model.dataBases.TreeData +import bstrees.model.dataBases.converters.utils.ComparableStringConverter +import bstrees.model.dataBases.converters.utils.StringConverter +import bstrees.model.trees.BSTree +import bstrees.model.trees.BSNode + +abstract class TreeToDataConverter< + K : Comparable, V, M, + NODE_TYPE : BSNode, + TREE_TYPE : BSTree>( + val keyStringConverter: ComparableStringConverter, + val valueStringConverter: StringConverter, + val keyType: String, + val valueType: String, +) { + abstract fun serializeTree(tree: TREE_TYPE, treeName: String): TreeData + + abstract fun deserializeTree(tree: TreeData): TREE_TYPE + + protected fun linkParents(node: NODE_TYPE) { + node.leftNode?.parent = node + node.rightNode?.parent = node + node.leftNode?.let { linkParents(it) } + node.rightNode?.let { linkParents(it) } + } +} diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/AvlToDataConverter.kt b/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/AvlToDataConverter.kt new file mode 100644 index 0000000..cb576dd --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/AvlToDataConverter.kt @@ -0,0 +1,60 @@ +package bstrees.model.dataBases.converters.treesConverters + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import bstrees.model.dataBases.converters.TreeToDataConverter +import bstrees.model.dataBases.converters.utils.ComparableStringConverter +import bstrees.model.dataBases.converters.utils.StringConverter +import bstrees.model.trees.avl.AvlNode +import bstrees.model.trees.avl.AvlTree + +class AvlToDataConverter, V>( + keyStringConverter: ComparableStringConverter, + valueStringConverter: StringConverter, + keyType: String, + valueType: String, +) : TreeToDataConverter, AvlTree>( + keyStringConverter, + valueStringConverter, + keyType, + valueType, +) { + private fun serializeNode(node: AvlNode): NodeData = NodeData( + keyStringConverter.toString(node.key), + valueStringConverter.toString(node.value), + serializeMetadata(node.height), + 0, + 0, + node.leftNode?.let { serializeNode(it) }, + node.rightNode?.let { serializeNode(it) } + ) + + private fun deserializeNode(node: NodeData): AvlNode { + val avlnode: AvlNode = AvlNode(keyStringConverter.fromString(node.key), valueStringConverter.fromString(node.value)) + if (node.metadata[0] != 'H') throw Exception("Wrong metadata. Impossible to deserialize") + avlnode.height = deserializeMetadata(node.metadata) + avlnode.leftNode = node.leftNode?.let { deserializeNode(it) } + avlnode.rightNode = node.rightNode?.let { deserializeNode(it) } + linkParents(avlnode) + return avlnode + } + + override fun serializeTree(tree: AvlTree, treeName: String) = TreeData( + name = treeName, + treeType = "AVL", + keyType = keyType, + valueType = valueType, + root = tree.root?.let { serializeNode(it) } + ) + + override fun deserializeTree(tree: TreeData): AvlTree { + if (tree.treeType != "AVL") throw Exception("Wrong tree type. Impossible to deserialize") + val avltree = AvlTree() + avltree.root = tree.root?.let { deserializeNode(it) } + return avltree + } + + private fun serializeMetadata(meta: Int) = "H$meta" + + private fun deserializeMetadata(meta: String) = meta.substring(1).toInt() +} diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/RandomBsToDataConverter.kt b/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/RandomBsToDataConverter.kt new file mode 100644 index 0000000..663e350 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/RandomBsToDataConverter.kt @@ -0,0 +1,61 @@ +package bstrees.model.dataBases.converters.treesConverters + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import bstrees.model.dataBases.converters.TreeToDataConverter +import bstrees.model.dataBases.converters.utils.ComparableStringConverter +import bstrees.model.dataBases.converters.utils.StringConverter +import bstrees.model.trees.randomBinarySearch.RandomBSNode +import bstrees.model.trees.randomBinarySearch.RandomBSTree + +class RandomBsToDataConverter, V>( + keyStringConverter: ComparableStringConverter, + valueStringConverter: StringConverter, + keyType: String, + valueType: String, +) : TreeToDataConverter, RandomBSTree>( + keyStringConverter, + valueStringConverter, + keyType, + valueType +) { + + private fun serializeNode(node: RandomBSNode): NodeData = NodeData( + keyStringConverter.toString(node.key), + valueStringConverter.toString(node.value), + serializeMetadata(node.size), + 0, + 0, + node.leftNode?.let { serializeNode(it) }, + node.rightNode?.let { serializeNode(it) } + ) + + private fun deserializeNode(node: NodeData): RandomBSNode { + val bsnode: RandomBSNode = RandomBSNode(keyStringConverter.fromString(node.key), valueStringConverter.fromString(node.value)) + if (node.metadata[0] != 'S') throw Exception("Wrong metadata. Impossible to deserialize") + bsnode.size = deserializeMetadata(node.metadata) + bsnode.leftNode = node.leftNode?.let { deserializeNode(it) } + bsnode.rightNode = node.rightNode?.let { deserializeNode(it) } + linkParents(bsnode) + return bsnode + } + + override fun serializeTree(tree: RandomBSTree, treeName: String) = TreeData( + name = treeName, + treeType = "BS", + keyType = keyType, + valueType = valueType, + root = tree.root?.let { serializeNode(it) } + ) + + override fun deserializeTree(tree: TreeData): RandomBSTree { + if (tree.treeType != "BS") throw Exception("Wrong tree type. Impossible to deserialize") + val bstree = RandomBSTree() + bstree.root = tree.root?.let { deserializeNode(it) } + return bstree + } + + private fun serializeMetadata(meta: Int) = "S$meta" + + private fun deserializeMetadata(meta: String) = meta.substring(1).toInt() +} diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/RbToDataConverter.kt b/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/RbToDataConverter.kt new file mode 100644 index 0000000..089bb8e --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/converters/treesConverters/RbToDataConverter.kt @@ -0,0 +1,61 @@ +package bstrees.model.dataBases.converters.treesConverters + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import bstrees.model.dataBases.converters.TreeToDataConverter +import bstrees.model.dataBases.converters.utils.ComparableStringConverter +import bstrees.model.dataBases.converters.utils.StringConverter +import bstrees.model.trees.redBlack.RBNode +import bstrees.model.trees.redBlack.RBTree +import bstrees.model.trees.redBlack.RBNode.Color + +class RbToDataConverter, V>( + keyStringConverter: ComparableStringConverter, + valueStringConverter: StringConverter, + keyType: String, + valueType: String, +) : TreeToDataConverter, RBTree>( + keyStringConverter, + valueStringConverter, + keyType, + valueType, +) { + private fun serializeNode(node: RBNode): NodeData = NodeData( + keyStringConverter.toString(node.key), + valueStringConverter.toString(node.value), + serializeMetadata(node.color), + 0, + 0, + node.leftNode?.let { serializeNode(it) }, + node.rightNode?.let { serializeNode(it) } + ) + + private fun deserializeNode(node: NodeData): RBNode { + val rbnode: RBNode = RBNode(keyStringConverter.fromString(node.key), valueStringConverter.fromString(node.value)) + if (node.metadata != "RED" && node.metadata != "BLACK") throw Exception("Wrong metadata. Impossible to deserialize") + rbnode.color = deserializeMetadata(node.metadata) + rbnode.leftNode = node.leftNode?.let { deserializeNode(it) } + rbnode.rightNode = node.rightNode?.let { deserializeNode(it) } + linkParents(rbnode) + return rbnode + } + + override fun serializeTree(tree: RBTree, treeName: String) = TreeData( + name = treeName, + treeType = "RB", + keyType = keyType, + valueType = valueType, + root = tree.root?.let { serializeNode(it) } + ) + + override fun deserializeTree(tree: TreeData): RBTree { + if (tree.treeType != "RB") throw Exception("Wrong tree type. Impossible to deserialize") + val rbtree = RBTree() + rbtree.root = tree.root?.let { deserializeNode(it) } + return rbtree + } + + private fun deserializeMetadata(meta: String): Color = if (meta == "RED") Color.RED else Color.BLACK + + private fun serializeMetadata(meta: Color): String = if (meta == Color.RED) "RED" else "BLACK" +} diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/converters/utils/StringConverter.kt b/lib/src/main/kotlin/bstrees/model/dataBases/converters/utils/StringConverter.kt new file mode 100644 index 0000000..0f44a11 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/converters/utils/StringConverter.kt @@ -0,0 +1,27 @@ +package bstrees.model.dataBases.converters.utils + +interface StringConverter { + fun toString(value: T): String + fun fromString(value: String): T +} + +interface ComparableStringConverter>: StringConverter + +object StringStringConverter : ComparableStringConverter { + override fun toString(value: String): String = value + + override fun fromString(value: String): String = value +} + +object IntStringConverter : ComparableStringConverter { + override fun toString(value: Int): String = value.toString() + + override fun fromString(value: String): Int = value.toInt() +} + +fun createStringConverter(type: String): ComparableStringConverter<*> = when (type) { + "String" -> StringStringConverter + "Int" -> IntStringConverter + else -> throw IllegalArgumentException("Unsupported type $type") +} + diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/reps/JsonTreeRepo.kt b/lib/src/main/kotlin/bstrees/model/dataBases/reps/JsonTreeRepo.kt new file mode 100644 index 0000000..21e4869 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/reps/JsonTreeRepo.kt @@ -0,0 +1,85 @@ +package bstrees.model.dataBases.reps + +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.json.Json +import bstrees.model.dataBases.TreeData +import kotlinx.serialization.encodeToString +import mu.KotlinLogging +import java.io.* +import kotlin.io.path.Path + +private val logger = KotlinLogging.logger { } + + +class JsonTreeRepo(private val dir: String) : TreeRepo { + + init { + makeDir(dir) + logger.info { "[JSON] Dir paths was created" } + } + + private fun makeDir(dir: String) { + File(dir).mkdir() + File(Path(dir, "BS").toUri()).mkdir() + File(Path(dir, "RB").toUri()).mkdir() + File(Path(dir, "AVL").toUri()).mkdir() + } + + private fun getPathToFile(treeName: String, typeTree: String): String { + return Path(dir, typeTree, "${treeName}.json").toString() + } + + override fun getTree(treeName: String, treeType: String): TreeData? { + val filePath = getPathToFile(treeName, treeType) + lateinit var file: FileReader + var fileFound = true + + return try { + file = FileReader(filePath) + val jsonText = file.readText() + + Json.decodeFromString(jsonText) + } catch (e: FileNotFoundException) { + logger.warn { "[JSON] Tree file not found" } + fileFound = false + null + } catch (e: Exception) { + logger.error { "[JSON] Error getting the tree: $e" } + throw e + } finally { + if (fileFound) { + file.close() + logger.info { "[JSON] Got tree - treeName: $treeName, treeType: $treeType" } + } + } + } + + override fun setTree(treeData: TreeData) { + val filePath = getPathToFile(treeData.name, treeData.treeType) + lateinit var file: FileWriter + + try { + file = FileWriter(filePath) + file.write(Json.encodeToString(treeData)) + } catch (e: Exception) { + logger.error { "[JSON] Error getting the tree: $e" } + throw e + } finally { + file.flush() + file.close() + } + logger.info { "[JSON] Set tree - treeName: ${treeData.name}, treeType: ${treeData.treeType}" } + } + + override fun deleteTree(treeName: String, treeType: String) { + val path = getPathToFile(treeName, treeType) + + try { + File(path).delete() + } catch (e: Exception) { + logger.error { "[JSON] Error getting the tree: $e" } + throw e + } + logger.info { "[JSON] Deleted tree - treeName: $treeName, treeType: $treeType" } + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/reps/Neo4jTreeRepo.kt b/lib/src/main/kotlin/bstrees/model/dataBases/reps/Neo4jTreeRepo.kt new file mode 100644 index 0000000..0344b42 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/reps/Neo4jTreeRepo.kt @@ -0,0 +1,201 @@ +package bstrees.model.dataBases.reps + +import mu.KotlinLogging +import org.neo4j.driver.AuthTokens +import org.neo4j.driver.GraphDatabase +import org.neo4j.driver.TransactionContext +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import java.io.Closeable + +private val logger = KotlinLogging.logger { } + +class Neo4jTreeRepo(host: String, username: String, password: String) : Closeable, TreeRepo { + private val driver = GraphDatabase.driver(host, AuthTokens.basic(username, password)) + private val session = driver.session() + + override fun getTree(treeName: String, treeType: String): TreeData? { + var treeData: TreeData? = null + + session.executeRead { tx -> + val resultTreeInfo = tx.run( + "MATCH (tree: Tree {name: \$name, type: \$type}) RETURN tree.keyType as keyType, tree.valueType as valueType", + mutableMapOf( + "name" to treeName, + "type" to treeType, + ) as Map? + ) + val resultRootKey = tx.run( + "MATCH (tree: Tree {name: \$name, type: \$type}) " + + "WITH tree MATCH (tree)-[:root]->(root) RETURN root.key AS rootKey", + mutableMapOf( + "name" to treeName, + "type" to treeType, + ) as Map? + ) + + var rootKey = "" + if (resultRootKey.hasNext()) { + val info: Map = resultRootKey.next().asMap() + rootKey = info["rootKey"].toString() + } + + if (resultTreeInfo.hasNext()) { + val info: Map = resultTreeInfo.next().asMap() + treeData = TreeData( + treeName, + treeType, + info["keyType"].toString(), + info["valueType"].toString(), + if (rootKey != "") getSerializedNodes(tx, rootKey) else null + ) + } + } + + logger.info { "[NEO4J] Got tree - treeName: $treeName, treeType: $treeType" } + + return treeData + } + + + private fun getSerializedNodes(tx: TransactionContext, nodeKey: String): NodeData? { + var nodeData = mapOf() + var leftSonKey = mapOf() + var rightSonKey = mapOf() + + val resultNodeData = tx.run( + "MATCH (node:Node {key: \$nodeKey}) RETURN node.key AS key, node.value AS value, node.metadata AS metadata, node.posX AS posX, node.posY AS posY", + mutableMapOf( + "nodeKey" to nodeKey, + ) as Map? + ) + val resultLeftSonKey = tx.run( + "MATCH (node:Node {key: \$nodeKey}) MATCH (node)-[:leftSon]->(leftSon) RETURN leftSon.key as key", + mutableMapOf( + "nodeKey" to nodeKey, + ) as Map? + ) + val resultRightSonKey = tx.run( + "MATCH (node:Node {key: \$nodeKey}) MATCH (node)-[:rightSon]->(rightSon) RETURN rightSon.key as key", + mutableMapOf( + "nodeKey" to nodeKey, + ) as Map? + ) + + if (resultNodeData.hasNext()) { + nodeData = resultNodeData.next().asMap() + } + if (resultLeftSonKey.hasNext()) { + leftSonKey = resultLeftSonKey.next().asMap() + } + if (resultRightSonKey.hasNext()) { + rightSonKey = resultRightSonKey.next().asMap() + } + + if (nodeData.isEmpty()) return null + return NodeData( + nodeData["key"].toString(), + nodeData["value"].toString(), + nodeData["metadata"].toString(), + nodeData["posX"].toString().toInt(), + nodeData["posY"].toString().toInt(), + getSerializedNodes(tx, leftSonKey["key"].toString()), + getSerializedNodes(tx, rightSonKey["key"].toString()), + ) + } + + override fun setTree(treeData: TreeData) { + + deleteTree(treeData.name, treeData.treeType) + + session.executeWrite { tx -> + tx.run( + "CREATE (:Tree {name: \$name, type: \$type, keyType: \$keyType, valueType: \$valueType})", + mutableMapOf( + "name" to treeData.name, + "type" to treeData.treeType, + "keyType" to treeData.keyType, + "valueType" to treeData.valueType, + ) as Map? + ) + + treeData.root?.let { root -> + setNeo4jNodes(tx, root) + tx.run( + "MATCH (tree: Tree {name: \$name, type: \$type}) " + + "MATCH (node: NewNode {key: \$rootKey }) " + + "CREATE (tree)-[:root]->(node) " + + "REMOVE node:NewNode", + mutableMapOf( + "name" to treeData.name, + "type" to treeData.treeType, + "rootKey" to root.key, + ) as Map? + ) + } + } + + logger.info { "[NEO4J] Set tree - treeName: ${treeData.name}, treeType: ${treeData.treeType}" } + } + + private fun setNeo4jNodes(tx: TransactionContext, node: NodeData) { + tx.run( + "CREATE (:Node:NewNode {key: \$nodeKey, value: \$nodeValue, " + + "metadata: \$nodeMetadata, posX: ${node.posX}, posY: ${node.posY} })", + mutableMapOf( + "nodeKey" to node.key, + "nodeValue" to node.value, + "nodeMetadata" to node.metadata, + ) as Map? + ) + node.leftNode?.let { leftNode -> + setNeo4jNodes(tx, leftNode) + tx.run( + "MATCH (node: NewNode {key: \$nodeKey}) " + + "MATCH (leftSon: NewNode {key: \$leftNodeKey}) " + + "CREATE (node)-[:leftSon]->(leftSon) " + + "REMOVE leftSon:NewNode", + mutableMapOf( + "nodeKey" to node.key, + "leftNodeKey" to leftNode.key, + ) as Map? + ) + } + node.rightNode?.let { rightNode -> + setNeo4jNodes(tx, rightNode) + tx.run( + "MATCH (node: NewNode {key: \$nodeKey}) " + + "MATCH (rightSon: NewNode {key: \$rightNodeKey}) " + + "CREATE (node)-[:rightSon]->(rightSon) " + + "REMOVE rightSon:NewNode", + mutableMapOf( + "nodeKey" to node.key, + "rightNodeKey" to rightNode.key, + ) as Map? + ) + } + } + + override fun deleteTree(treeName: String, treeType: String) { + session.executeWrite { tx -> + tx.run( + "MATCH (tree: Tree {name: \$name, type: \$type}) " + + "MATCH (tree)-[*]->(node:Node) " + + "DETACH DELETE tree, node", + mutableMapOf( + "name" to treeName, + "type" to treeType, + ) as Map? + ) + } + + logger.info { "[NEO4J] Deleted tree - treeName: $treeName, treeType: $treeType" } + } + + override fun close() { + session.close() + driver.close() + + logger.info { "[NEO4J] The connection to the database is finished" } + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/reps/SQLTreeRepo.kt b/lib/src/main/kotlin/bstrees/model/dataBases/reps/SQLTreeRepo.kt new file mode 100644 index 0000000..dbaf025 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/reps/SQLTreeRepo.kt @@ -0,0 +1,169 @@ +package bstrees.model.dataBases.reps + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData +import mu.KotlinLogging +import org.jetbrains.exposed.sql.Database +import org.jetbrains.exposed.sql.SchemaUtils +import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq +import org.jetbrains.exposed.sql.and +import org.jetbrains.exposed.sql.transactions.transaction +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 +import org.jetbrains.exposed.sql.ReferenceOption +import java.io.File + + +private val logger = KotlinLogging.logger { } + +object TreesTable : IntIdTable() { + val treeName = varchar("nameTree", 20) + val treeType = varchar("typeTree", 20) + val keyType = varchar("keyType", 20) + val valueType = varchar("valueType", 20) + val root = reference("root", NodesTable).nullable() +} + +class TreeEntity(id: EntityID) : IntEntity(id) { + companion object : IntEntityClass(TreesTable) + + var treeName by TreesTable.treeName + var treeType by TreesTable.treeType + var keyType by TreesTable.keyType + var valueType by TreesTable.valueType + var root by NodeEntity optionalReferencedOn TreesTable.root +} + +object NodesTable : IntIdTable() { + val key = varchar("key", 255) + val value = varchar("value", 255) + val metadata = varchar("metadata", 255) + val leftNode = reference("leftNode", NodesTable).nullable() + val rightNode = reference("rightNode", NodesTable).nullable() + val posX = integer("posX") + val posY = integer("posY") + val tree = reference("tree", TreesTable, onDelete = ReferenceOption.CASCADE) +} + +class NodeEntity(id: EntityID) : IntEntity(id) { + companion object : IntEntityClass(NodesTable) + + var key by NodesTable.key + var value by NodesTable.value + var metadata by NodesTable.metadata + var leftNode by NodeEntity optionalReferencedOn NodesTable.leftNode + var rightNode by NodeEntity optionalReferencedOn NodesTable.rightNode + var posX by NodesTable.posX + var posY by NodesTable.posY + var tree by TreeEntity referencedOn NodesTable.tree +} + +class SQLTreeRepo(dbName: String) : TreeRepo { + + init { + connectDB(dbName) + createTables() + } + + private fun connectDB(dbName: String) { + Database.connect("jdbc:sqlite:${File(dbName)}", "org.sqlite.JDBC") + + logger.info { "[SQLite] The connection to the database is established" } + } + + private fun createTables() { + transaction { + SchemaUtils.create(TreesTable) + SchemaUtils.create(NodesTable) + } + + logger.info { "[SQLite] Database tables have been created successfully" } + } + + override fun getTree(treeName: String, treeType: String): TreeData? { + var treeEntity: TreeEntity? = null + transaction { + treeEntity = TreeEntity.find { (TreesTable.treeName eq treeName) and (TreesTable.treeType eq treeType) } + .firstOrNull() + } + + if (treeEntity == null) { + logger.info { "[SQLite] Tree not found - treeName: $treeName, treeType: $treeType" } + return null + } + + var treeData: TreeData? = null + transaction { + treeEntity?.let { tree -> + treeData = TreeData( + treeName, + tree.treeType, + tree.keyType, + tree.valueType, + tree.root?.toSerializableEntity(tree) + ) + } + } + + logger.info { "[SQLite] Got tree - treeName: $treeName, treeType: $treeType" } + + return treeData + } + + private fun NodeEntity.toSerializableEntity(treeEntity: TreeEntity): NodeData { + return NodeData( + this@toSerializableEntity.key, + this@toSerializableEntity.value, + this@toSerializableEntity.metadata, + this@toSerializableEntity.posX, + this@toSerializableEntity.posY, + this@toSerializableEntity.leftNode?.toSerializableEntity(treeEntity), + this@toSerializableEntity.rightNode?.toSerializableEntity(treeEntity), + ) + } + + override fun setTree(treeData: TreeData) { + deleteTree(treeData.name, treeData.treeType) + + transaction { + val newTree = TreeEntity.new { + treeName = treeData.name + treeType = treeData.treeType + keyType = treeData.keyType + valueType = treeData.valueType + } + + newTree.root = treeData.root?.toNodeEntity(newTree) + } + + logger.info { "[SQLite] Set tree - treeName: ${treeData.name}, treeType: ${treeData.treeType}" } + } + + private fun NodeData.toNodeEntity(treeEntity: TreeEntity): NodeEntity { + return NodeEntity.new { + key = this@toNodeEntity.key + value = this@toNodeEntity.value + metadata = this@toNodeEntity.metadata + leftNode = this@toNodeEntity.leftNode?.toNodeEntity(treeEntity) + rightNode = this@toNodeEntity.rightNode?.toNodeEntity(treeEntity) + posX = this@toNodeEntity.posX + posY = this@toNodeEntity.posY + tree = treeEntity + } + } + + override fun deleteTree(treeName: String, treeType: String) { + transaction { + val treeEntity = + TreeEntity.find { (TreesTable.treeName eq treeName) and (TreesTable.treeType eq treeType) } + .firstOrNull() + treeEntity?.let { NodeEntity.find(NodesTable.tree eq treeEntity.id).forEach { it.delete() } } + + treeEntity?.delete() + } + + logger.info { "[SQLite] Deleted tree - treeName: $treeName, treeType: $treeType" } + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/bstrees/model/dataBases/reps/TreeRepo.kt b/lib/src/main/kotlin/bstrees/model/dataBases/reps/TreeRepo.kt new file mode 100644 index 0000000..041acb2 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/dataBases/reps/TreeRepo.kt @@ -0,0 +1,11 @@ +package bstrees.model.dataBases.reps + +import bstrees.model.dataBases.TreeData + +interface TreeRepo { + fun getTree(treeName: String, treeType: String): TreeData? + + fun setTree(treeData: TreeData) + + fun deleteTree(treeName: String, treeType: String) +} \ No newline at end of file diff --git a/lib/src/main/kotlin/bstrees/model/trees/BSNode.kt b/lib/src/main/kotlin/bstrees/model/trees/BSNode.kt new file mode 100644 index 0000000..6e8b4c7 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/BSNode.kt @@ -0,0 +1,29 @@ +package bstrees.model.trees + +/** + * An abstract class representing a binary search tree node. + * It's constructed with key and value and contains parent, left and right sons + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + * @generic the type of node used in the tree + */ +abstract class BSNode, V, NODE_TYPE : BSNode>(val key: K, var value: V) { + /** + * The parent of the node + */ + var parent: NODE_TYPE? = null + internal set + + /** + * The left son of the node + */ + var leftNode: NODE_TYPE? = null + internal set + + /** + * The right son of the node + */ + var rightNode: NODE_TYPE? = null + internal set +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/BSTree.kt b/lib/src/main/kotlin/bstrees/model/trees/BSTree.kt new file mode 100644 index 0000000..7a0ef5f --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/BSTree.kt @@ -0,0 +1,50 @@ +package bstrees.model.trees + +/** + * An abstract class representing a binary search tree. + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + * @generic the type of node used in the tree + */ +abstract class BSTree, V, NODE_TYPE : BSNode> { + /** + * The root node of the tree. + */ + var root: NODE_TYPE? = null + internal set + + /** + * Insert a node to the tree. + * + * @param value the value to add + * @param key the key under which the value is stored + */ + abstract fun insert(key: K, value: V) + + /** + * Looking for a value in the tree by its key. + * + * @param key the key by which the search is performed + * @return value if it is in the tree, false otherwise + */ + fun find(key: K): V? { + var temp: NODE_TYPE? = root ?: return null + while (temp != null) { + if (temp.key == key) return temp.value + temp = if (temp.key > key) { + temp.leftNode + } else { + temp.rightNode + } + } + return null + } + + /** + * Delete a value from the tree. + * + * @param key the key under which the value is stored + */ + abstract fun delete(key: K) +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/Balancer.kt b/lib/src/main/kotlin/bstrees/model/trees/Balancer.kt new file mode 100644 index 0000000..f6345ef --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/Balancer.kt @@ -0,0 +1,56 @@ +package bstrees.model.trees + +/** + * An abstract class representing a binary search tree. + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + * @generic the type of node used in the tree + */ +abstract class Balancer, V, NODE_TYPE : BSNode> { + /** + * Do a left rotate around this node + * + * @param node the node around which the rotation is done + */ + protected fun leftRotate(node: NODE_TYPE): NODE_TYPE { + + val nodeParent = node.parent + val temp = node.rightNode + + temp?.parent = nodeParent + //We should change parent's son. It depends on what son is our node + if (nodeParent?.leftNode == node) nodeParent.leftNode = temp else nodeParent?.rightNode = temp + + node.rightNode = temp?.leftNode + node.rightNode?.parent = node + + temp?.leftNode = node + node.parent = temp + + return temp ?: node + } + + /** + * Do a right rotate around this node + * + * @param node the node around which the rotation is done + */ + protected fun rightRotate(node: NODE_TYPE): NODE_TYPE { + + val nodeParent = node.parent + val temp = node.leftNode + + temp?.parent = nodeParent + //We should change parent's son. It depends on what son is our node + if (nodeParent?.leftNode == node) nodeParent.leftNode = temp else nodeParent?.rightNode = temp + + node.leftNode = temp?.rightNode + node.leftNode?.parent = node + + temp?.rightNode = node + node.parent = temp + + return temp ?: node + } +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/avl/AvlBalancer.kt b/lib/src/main/kotlin/bstrees/model/trees/avl/AvlBalancer.kt new file mode 100644 index 0000000..d58bb1b --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/avl/AvlBalancer.kt @@ -0,0 +1,86 @@ +package bstrees.model.trees.avl + +import bstrees.model.trees.Balancer + +/** + * A class representing an AVL binary search tree balancer. + * Provides all the necessary functions for balancing the tree + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +internal class AvlBalancer, V> : Balancer>() { + + /** + * Provides information about the need for balancing by calculating the imbalance of the tree + * + * @param node node that has been checked + */ + private fun balanceFactor(node: AvlNode): Int { + return (node.rightNode?.height ?: 0) - (node.leftNode?.height ?: 0) + } + + /** + * Do a right rotate around this node with updating height + * + * @param node the node around which the rotation is done + */ + private fun avlRightRotate(node: AvlNode): AvlNode { + val temp = rightRotate(node) + temp.leftNode?.updateHeight() + temp.rightNode?.updateHeight() + temp.updateHeight() + return temp + } + + /** + * Do a left rotate around this node with updating height + * + * @param node the node around which the rotation is done + */ + private fun avlLeftRotate(node: AvlNode): AvlNode { + val temp = leftRotate(node) + temp.leftNode?.updateHeight() + temp.rightNode?.updateHeight() + temp.updateHeight() + return temp + } + + /** + * Balance current node + * + * @param node node that are balanced + */ + internal fun balance(node: AvlNode): AvlNode { + + node.updateHeight() + val bf = balanceFactor(node) + + if (bf == 2) { + + val temp = node.rightNode + if (temp != null) { + if (balanceFactor(temp) < 0) { + node.rightNode = avlRightRotate(temp)//big left rotate + } + } + + return avlLeftRotate(node) + } + + if (bf == -2) { + + val temp = node.leftNode + if (temp != null) { + if (balanceFactor(temp) > 0) { + node.leftNode = avlLeftRotate(temp)//big right rotate + } + } + + return avlRightRotate(node) + } + + return node + } + +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/avl/AvlNode.kt b/lib/src/main/kotlin/bstrees/model/trees/avl/AvlNode.kt new file mode 100644 index 0000000..2ec188c --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/avl/AvlNode.kt @@ -0,0 +1,28 @@ +package bstrees.model.trees.avl + +import bstrees.model.trees.BSNode +import kotlin.math.max + +/** + * A class representing an AVL binary search tree node. + * The difference from the abstract node class is in the presence of a height and the function of updating it + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +class AvlNode, V>(key: K, value: V) : BSNode>(key, value) { + + /** + * The variable that contains a height of the tree + */ + internal var height = 1 + + /** + * Update a height of the tree to set the correct value + */ + fun updateHeight() { + val leftHeight = this.leftNode?.height ?: 0 + val rightHeight = this.rightNode?.height ?: 0 + height = (max(leftHeight, rightHeight) + 1) + } +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/avl/AvlTree.kt b/lib/src/main/kotlin/bstrees/model/trees/avl/AvlTree.kt new file mode 100644 index 0000000..2591669 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/avl/AvlTree.kt @@ -0,0 +1,172 @@ +package bstrees.model.trees.avl + +import bstrees.model.trees.BSTree + +/** + * A class representing an AVL binary search tree. + * It maintains balance by checking heights of right and left sons. It has to differ by no more than one + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +class AvlTree, V> : BSTree>() { + + /** + * A balancer class providing balancing of the current node of the tree + */ + private val balancer = AvlBalancer() + + /** + * Insert a node to the tree. + * It is actually a wrapper for the add function. Necessary to implement recursion + * + * @param value the value to add + * @param key the key under which the value is stored + */ + override fun insert(key: K, value: V) { + add(AvlNode(key, value)) + } + + /** + * Add a node to the tree + * + * @param node the node to add + */ + private fun add(node: AvlNode) { + //temp is needed to avoid possibility of changing the root + val temp = this.root + if (temp == null) this.root = node + else if (temp.key == node.key) this.root?.value = node.value + else { + + /** + * Some kind of recursive implementation + * Creating subtree to execute add function again + * Then we return the node to the desired son + */ + val subTree = AvlTree() + + if (node.key < temp.key) { + subTree.root = temp.leftNode + subTree.add(node) + subTree.root?.parent = this.root + this.root?.leftNode = subTree.root + } else if (node.key > temp.key) { + subTree.root = temp.rightNode + subTree.add(node) + subTree.root?.parent = this.root + this.root?.rightNode = subTree.root + } + + } + + //Balancing this node before leaving recursion + this.root = this.root?.let { balancer.balance(it) } + } + + /** + * Find a node with a minimum key in a tree + * It is an auxiliary function for the delete function + * + * @param node the root of the tree where to find the minimum node + */ + private fun findMin(node: AvlNode): AvlNode { + //temp is needed to avoid possibility of changing the root + val temp = node.leftNode + return if (temp != null) findMin(temp) else node + } + + /** + * Find a node with a minimum key in a tree and delete it. + * It is an auxiliary function for the delete function + * + * @param node the root of the tree where to remove the minimum node + */ + private fun removeMin(node: AvlNode): AvlNode? { + //temp is needed to avoid possibility of changing the root + val temp = node.leftNode + if (temp == null) return node.rightNode + + val tempRemovedMin = removeMin(temp) + node.leftNode = tempRemovedMin + tempRemovedMin?.parent = node + return balancer.balance(node) + } + + /** + * Delete a value from the tree. + * + * @param key the key under which the value is stored + */ + override fun delete(key: K) { + //temp is needed to avoid possibility of changing the root + val temp = this.root + + if (temp != null) { + /** + * Some kind of recursive implementation + * Creating subtree to execute delete function again + * Then we return the node to the desired son + */ + val subTree = AvlTree() + + if (key < temp.key) { + + subTree.root = temp.leftNode + subTree.delete(key) + subTree.root?.parent = this.root + this.root?.leftNode = subTree.root + + } else if (key > temp.key) { + + subTree.root = temp.rightNode + subTree.delete(key) + subTree.root?.parent = this.root + this.root?.rightNode = subTree.root + + } else { + //The left and right sons of the node being deleted + val left = this.root?.leftNode + val right = this.root?.rightNode + + if (right == null) { + left?.parent = this.root?.parent + this.root = left + } else { + /** + * Temp is needed to avoid possibility of changing the root + * + * Finding the minimum node and giving her the correct links to the sons and the parent + */ + val tempMin = findMin(right) + tempMin.rightNode = removeMin(right) + tempMin.rightNode?.parent = tempMin + tempMin.leftNode = left + tempMin.leftNode?.parent = tempMin + + /** + * Giving correct links to the new node for the parent + * The son recognizes the parent, but the parent of the son does not + */ + if (this.root?.parent?.leftNode == this.root) this.root?.parent?.leftNode = tempMin + else this.root?.parent?.rightNode = tempMin + + tempMin.parent = this.root?.parent + /** + * Balancing th new node + * + * Everything at the bottom is already balanced, + * because it was done coming out of recursion + */ + this.root = balancer.balance(tempMin) + } + + } + + //Balancing this node before leaving recursion + val nullCheck = this.root + if (nullCheck != null) this.root = balancer.balance(nullCheck) + + } + } +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSBalancer.kt b/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSBalancer.kt new file mode 100644 index 0000000..e044635 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSBalancer.kt @@ -0,0 +1,40 @@ +package bstrees.model.trees.randomBinarySearch + +import bstrees.model.trees.Balancer + +/** + * A class representing a randomized binary search tree balancer. + * Provides all the necessary functions for rotating the tree + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +internal class RandomBSBalancer, V> : Balancer>() { + + /** + * Do a right rotate around this node with updating size + * + * @param node the node around which the rotation is done + */ + internal fun bsRightRotate(node: RandomBSNode): RandomBSNode { + val temp = rightRotate(node) + temp.leftNode?.updateSize() + temp.rightNode?.updateSize() + temp.updateSize() + return temp + } + + /** + * Do a left rotate around this node with updating size + * + * @param node the node around which the rotation is done + */ + internal fun bsLeftRotate(node: RandomBSNode): RandomBSNode { + val temp = leftRotate(node) + temp.leftNode?.updateSize() + temp.rightNode?.updateSize() + temp.updateSize() + return temp + } + +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSNode.kt b/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSNode.kt new file mode 100644 index 0000000..c717c4d --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSNode.kt @@ -0,0 +1,29 @@ +package bstrees.model.trees.randomBinarySearch + +import bstrees.model.trees.BSNode + +/** + * A class representing a randomized binary search tree node. + * The difference from the abstract node class is in the presence of size and the function of updating it + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +class RandomBSNode, V>(key: K, value: V) : BSNode>(key, value) { + + /** + * The variable that contains size of the tree + * It isn't a height. + * This variable contains the height, which is measured in the number of nodes in the tree including the root + */ + internal var size = 1 + + /** + * Update size of the tree to set the correct value + */ + fun updateSize() { + val leftSize = leftNode?.size ?: 0 + val rightSize = rightNode?.size ?: 0 + size = leftSize + rightSize + 1 + } +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSTree.kt b/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSTree.kt new file mode 100644 index 0000000..6593ec6 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/randomBinarySearch/RandomBSTree.kt @@ -0,0 +1,174 @@ +package bstrees.model.trees.randomBinarySearch + +import bstrees.model.trees.BSTree +import kotlin.random.Random + +/** + * A class representing a randomized binary search tree. + * + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +class RandomBSTree, V> : BSTree>() { + + /** + * A balancer class providing rotations of the tree with updating the size + */ + private val balancer = RandomBSBalancer() + + /** + * Insert a node to the tree. + * It is actually a wrapper for the add function. Necessary to implement recursion + * + * @param value the value to add + * @param key the key under which the value is stored + */ + override fun insert(key: K, value: V) { + add(RandomBSNode(key, value)) + } + + /** + * Add a node to the root of the tree. + * It's necessary to implement random adding. + * + * @param node the node to add + */ + private fun addRoot(node: RandomBSNode): RandomBSNode { + //temp is needed to avoid possibility of changing the root + val temp = this.root + return if (temp == null) node + else if (temp.key == node.key) { + temp.value = node.value + temp + } else { + /** + * Some kind of recursive implementation + * Creating subtree to execute add function again + * Then we return the node to the desired son + */ + val subTree = RandomBSTree() + //We make the usual adding, then we put the node in the root by rotation it tom the top + if (node.key < temp.key) { + subTree.root = temp.leftNode + this.root?.leftNode = subTree.addRoot(node) + balancer.bsRightRotate(temp) + } else { + subTree.root = temp.rightNode + this.root?.rightNode = subTree.addRoot(node) + balancer.bsLeftRotate(temp) + } + } + + } + + /** + * Add a node to the tree + * + * @param node the node to add + */ + private fun add(node: RandomBSNode) { + //temp is needed to avoid possibility of changing the root + val temp = this.root + if (temp == null) this.root = node + else if (temp.key == node.key) this.root?.value = node.value + else { + + if (Random.nextInt() % (node.size + 1) == 0) this.root = this.addRoot(node) + /* + Randomized insertion into the root of the tree allows you + to artificially balance it with a fairly small height. + The idea is that inserting into the root shuffles the tree well, which provides a relatively small height. + The tree is not perfectly balanced, but differs from the logarithm on average by no more than twice, + which is a constant + + Otherwise, we perform the usual insertion + */ + else { + /** + * Some kind of recursive implementation + * Creating subtree to execute add function again + * Then we return the node to the desired son + */ + val subTree = RandomBSTree() + if (temp.key > node.key) { + subTree.root = temp.leftNode + subTree.add(node) + subTree.root?.parent = this.root + this.root?.leftNode = subTree.root + } else { + subTree.root = temp.rightNode + subTree.add(node) + subTree.root?.parent = this.root + this.root?.rightNode = subTree.root + } + } + + //Updating this node before leaving recursion + this.root?.updateSize() + + } + } + + /** + * Merge two nodes into one. + * One of the ways to implement removal from the tree + * + * @param left + * @param right + * The nodes to merge + */ + private fun join(left: RandomBSNode?, right: RandomBSNode?): RandomBSNode? { + + //If one of the nodes is null then we can just return the second one + if (left == null) return right + if (right == null) return left + + //Choosing the node that would be a new root + return if (Random.nextInt() % (left.size + right.size) < left.size) { + left.rightNode = join(left.rightNode, right) + left.rightNode?.parent = left + left.updateSize() + left + } else { + right.leftNode = join(left, right.leftNode) + right.leftNode?.parent = right + right.updateSize() + right + } + + } + + /** + * Delete a value from the tree. + * + * @param key the key under which the value is stored + */ + override fun delete(key: K) { + + val temp = this.root + + if (temp != null) { + + if (temp.key == key) this.root = join(temp.leftNode, temp.rightNode) + else if (key < temp.key) { + val subTree = RandomBSTree() + subTree.root = temp.leftNode + subTree.delete(key) + subTree.root?.parent = this.root + this.root?.leftNode = subTree.root + } else { + val subTree = RandomBSTree() + subTree.root = temp.rightNode + subTree.delete(key) + subTree.root?.parent = this.root + this.root?.rightNode = subTree.root + } + + //Updating this node before leaving recursion + this.root?.updateSize() + + } + + } +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBBalancer.kt b/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBBalancer.kt new file mode 100644 index 0000000..a92fd91 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBBalancer.kt @@ -0,0 +1,219 @@ +package bstrees.model.trees.redBlack + +import bstrees.model.trees.Balancer +import bstrees.model.trees.redBlack.RBNode.Color + +/** + * A class representing a red black binary search tree balancer. + * Provides all the necessary functions for balancing the tree + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +open class RBBalancer, V> : Balancer>() { + + /** + * Balance the tree after deletion a red node. Starting from some node, + * we perform balancing and recursively climb up until we meet a black node + * for balancing or reach the root of the tree + * + * @param tree the tree we are balancing + * @param node the node from which we start balancing + */ + internal fun balanceAfterDeletion(tree: RBTree, node: RBNode) { + var curNode = node + var nodeParent = node.parent + while (nodeParent != null && curNode.color != Color.RED) { + + if (nodeParent.leftNode == curNode) { + + if (nodeParent.leftNode == null) { + curNode = nodeParent + nodeParent = curNode.parent + continue + } + + // brother MUST exist, because we have a 2xBLACK curNode in leftTree + var nodeBrother = nodeParent.rightNode ?: throw Exception("An attempt to take a non-existent son") + + // Consideration of the case 1. + // nodeBrother is red + if (nodeBrother.color == Color.RED) { + nodeBrother.color = Color.BLACK + nodeParent.color = Color.RED + if (nodeParent.parent == null) { + nodeParent = leftRotate(nodeParent) + tree.root = nodeParent + } else { + nodeParent = leftRotate(nodeParent) + } + + + // these nodes MUST exist because we did leftRotate with theirs nodes + nodeParent = nodeParent.leftNode ?: throw Exception("An attempt to take a non-existent son") + curNode = nodeParent.leftNode ?: throw Exception("An attempt to take a non-existent son") + nodeBrother = nodeParent.rightNode ?: throw Exception("An attempt to take a non-existent son") + } + + // Consideration of the case 2. + // nodeBrother's sons are black + val leftSonOfBrother = nodeBrother.leftNode + val rightSonOfBrother = nodeBrother.rightNode + if ((leftSonOfBrother == null || leftSonOfBrother.color == Color.BLACK) && + (rightSonOfBrother == null || rightSonOfBrother.color == Color.BLACK) + ) { + nodeBrother.color = Color.RED + curNode = nodeParent + nodeParent = curNode.parent + } else { + + // Consideration of the case 3. + // nodeBrother's left son is red, right son is black + if (leftSonOfBrother != null && leftSonOfBrother.color == Color.RED && (rightSonOfBrother == null || rightSonOfBrother.color == Color.BLACK)) { + nodeBrother.color = Color.RED + leftSonOfBrother.color = Color.BLACK + nodeBrother = rightRotate(nodeBrother) + } + + // Consideration of the case 4. + // nodeBrother's right son is red + nodeBrother.color = nodeParent.color + nodeParent.color = Color.BLACK + nodeBrother.rightNode?.color = Color.BLACK + if (nodeParent.parent == null) { + tree.root = leftRotate(nodeParent) + } else { + leftRotate(nodeParent) + } + break + } + } else { + + if (nodeParent.leftNode == null) { + curNode = nodeParent + nodeParent = curNode.parent + continue + } + + // brother MUST exist, because we have a 2xBLACK curNode in rightTree + var nodeBrother = nodeParent.leftNode ?: throw Exception("An attempt to take a non-existent son") + + // Consideration of the case 1. + // nodeBrother is red + if (nodeBrother.color == Color.RED) { + nodeBrother.color = Color.BLACK + nodeParent.color = Color.RED + + if (nodeParent.parent == null) { + nodeParent = rightRotate(nodeParent) + tree.root = nodeParent + } else { + nodeParent = rightRotate(nodeParent) + } + + // these nodes MUST exist because we did rightRotate with theirs nodes + nodeParent = nodeParent.rightNode ?: throw Exception("An attempt to take a non-existent son") + curNode = nodeParent.rightNode ?: throw Exception("An attempt to take a non-existent son") + nodeBrother = nodeParent.leftNode ?: throw Exception("An attempt to take a non-existent son") + } + + // Consideration of the case 2. + // nodeBrother's sons are black + val leftSonOfBrother = nodeBrother.leftNode + val rightSonOfBrother = nodeBrother.rightNode + if ((leftSonOfBrother == null || leftSonOfBrother.color == Color.BLACK) && + (rightSonOfBrother == null || rightSonOfBrother.color == Color.BLACK) + ) { + nodeBrother.color = Color.RED + curNode = nodeParent + nodeParent = curNode.parent + } else { + + // Consideration of the case 3. + // nodeBrother's left son is black, right son is red + if ((leftSonOfBrother == null || leftSonOfBrother.color == Color.BLACK) && rightSonOfBrother != null && rightSonOfBrother.color == Color.RED) { + nodeBrother.color = Color.RED + rightSonOfBrother.color = Color.BLACK + nodeBrother = leftRotate(nodeBrother) + } + + // Consideration of the case 4. + // nodeBrother's right son is red + nodeBrother.color = nodeParent.color + nodeParent.color = Color.BLACK + nodeBrother.leftNode?.color = Color.BLACK + if (nodeParent.parent == null) { + tree.root = rightRotate(nodeParent) + } else { + rightRotate(nodeParent) + } + break + } + } + } + curNode.color = Color.BLACK + } + + /** + * Balance the tree after adding a red node. Starting from some node, + * we perform balancing and recursively climb up until we meet a red parentNode + * for balancing or reach the root of the tree + * + * @param node the node from which we start balancing + */ + internal fun balanceAfterAdding(node: RBNode): RBNode { + var nodeParent = node.parent + var curNode = node + while (nodeParent != null && nodeParent.color == Color.RED) { + // It must exist, since the root of the tree cannot be red + val nodeGrandParent = nodeParent.parent ?: throw Exception("An attempt to take a non-existent parent") + + if (nodeParent == nodeGrandParent.leftNode) { + val nodeUncle = nodeGrandParent.rightNode + + if (nodeUncle == null || nodeUncle.color == Color.BLACK) { + if (curNode == nodeParent.rightNode) { + nodeParent = leftRotate(nodeParent) + curNode = nodeParent.leftNode ?: throw Exception("An attempt to take a non-existent son") + } + nodeParent.color = Color.BLACK + nodeGrandParent.color = Color.RED + rightRotate(nodeGrandParent) + } else { + nodeParent.color = Color.BLACK + nodeUncle.color = Color.BLACK + nodeGrandParent.color = Color.RED + + curNode = nodeGrandParent + nodeParent = curNode.parent + } + } else { + val nodeUncle = nodeGrandParent.leftNode + + if (nodeUncle == null || nodeUncle.color == Color.BLACK) { + if (curNode == nodeParent.leftNode) { + nodeParent = rightRotate(nodeParent) + curNode = nodeParent.rightNode ?: throw Exception("An attempt to take a non-existent son") + } + nodeParent.color = Color.BLACK + nodeGrandParent.color = Color.RED + leftRotate(nodeGrandParent) + } else { + nodeParent.color = Color.BLACK + nodeUncle.color = Color.BLACK + nodeGrandParent.color = Color.RED + + curNode = nodeGrandParent + nodeParent = curNode.parent + } + } + } + while (curNode.parent != null) { + curNode = curNode.parent ?: throw Exception("An attempt to take a non-existent parent") + } + + curNode.color = Color.BLACK + return curNode + } + +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBNode.kt b/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBNode.kt new file mode 100644 index 0000000..d0100cc --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBNode.kt @@ -0,0 +1,28 @@ +package bstrees.model.trees.redBlack + +import bstrees.model.trees.BSNode + +/** + * A class representing an AVL binary search tree node. + * The difference from the abstract node class is in the presence of a color which can be black of red + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +class RBNode, V>(key: K, value: V) : BSNode>(key, value) { + + /** + * An auxiliary enum class that contains the color of the node + * It can be only black or red + */ + enum class Color { + BLACK, + RED + } + + /** + * A variable that displays the current node color. + * It is always black by default + */ + internal var color = Color.BLACK +} diff --git a/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBTree.kt b/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBTree.kt new file mode 100644 index 0000000..1f4a578 --- /dev/null +++ b/lib/src/main/kotlin/bstrees/model/trees/redBlack/RBTree.kt @@ -0,0 +1,244 @@ +package bstrees.model.trees.redBlack + +import bstrees.model.trees.BSTree +import bstrees.model.trees.redBlack.RBNode.Color + +/** + * A class representing a red black binary search tree. + * It maintains balance through a strict hierarchy of red and black vertices, + * as well as some rules that they follow + * + * @generic the type of key stored in the tree. It must be comparable + * @generic the type of value stored in the tree + */ +class RBTree, V> : BSTree>() { + /** + * A balancer class providing balancing the tree when adding or deleting nodes + */ + private val balancer = RBBalancer() + + /** + * Insert a node to the tree. + * It is actually a wrapper for the add function. + * + * @param value the value to add + * @param key the key under which the value is stored + */ + override fun insert(key: K, value: V) { + add(RBNode(key, value)) + } + + /** + * Add a node to the root of the tree. + * + * @param node the node to add + */ + private fun add(node: RBNode) { + + // if a node with such a key already exists, then we update Value + val nodeWithEqualKey = findNodeByKey(node.key) + if (nodeWithEqualKey != null) { + nodeWithEqualKey.value = node.value + return + } + + var root = this.root + if (root == null) { + this.root = node + return + } + while (true) { + root ?: error("adding error") + if (root.key > node.key) { + val leftNode = root.leftNode + if (leftNode == null) { + node.color = Color.RED + root.leftNode = node + node.parent = root + this.root = balancer.balanceAfterAdding(node) + break + } else { + root = leftNode + } + } else { + val rightNode = root.rightNode + if (rightNode == null) { + node.color = Color.RED + root.rightNode = node + node.parent = root + this.root = balancer.balanceAfterAdding(node) + break + } else { + root = rightNode + } + } + } + } + + /** + * Looking for a node in the tree by its key. + * + * @param key the key by which the search is performed + */ + private fun findNodeByKey(key: K): RBNode? { + var temp: RBNode? = root ?: return null + while (temp != null) { + if (temp.key == key) return temp + temp = if (temp.key > key) { + temp.leftNode + } else { + temp.rightNode + } + } + return null + } + + /** + * Delete a value from the tree. + * + * @param key the key under which the value is stored + */ + override fun delete(key: K) { + // This is the node that needs to be deleted + val curNode = findNodeByKey(key) ?: return + + // This is the node that we will put in place of curNode + val nodeForSwapping = getNodeForSwapping(curNode) + + var sonIsNilNode = false + + // This is the node that will take the place of nodeForSwapping + // If nodeForSwapping has no sons, then we create an imaginary(Nil) sonNode + val sonNodeForSwapping = + if (nodeForSwapping.leftNode == null && nodeForSwapping.rightNode == null) { + sonIsNilNode = true + getNilNode(curNode) + } else { + if (nodeForSwapping.leftNode != null) nodeForSwapping.leftNode else nodeForSwapping.rightNode + } + + // We put the sonOfNodeForSwapping in the place of nodeForSwapping and establish the necessary links + setLinksWithSonOfNodeForSwapping(nodeForSwapping, sonNodeForSwapping, sonIsNilNode) + + val colorOfNodeForSwapping = nodeForSwapping.color + + // If nodeForSwapping != curNode, then we need to add the necessary links to nodeForSwapping to replace it. + if (curNode != nodeForSwapping) { + setLinksWithNodeForSwapping(curNode, nodeForSwapping) + nodeForSwapping.color = curNode.color + } + + // If the color of the deleted node is black, then we have to balance the tree + if (colorOfNodeForSwapping == Color.BLACK) { + sonNodeForSwapping?.let { balancer.balanceAfterDeletion(this, sonNodeForSwapping) } + } + + // If we used an imaginary(Nil) node, we have to remove unnecessary links + if (sonIsNilNode) { + if (sonNodeForSwapping?.parent?.leftNode == sonNodeForSwapping) { + sonNodeForSwapping?.parent?.leftNode = null + } else { + sonNodeForSwapping?.parent?.rightNode = null + } + } + } + + /** + * After we have selected a node that will take the place of the deleted one, + * we must specify all the links for the selected node. + * + * @param curNode the node that we are deleting + * @param nodeForSwapping the node that will stand in place of the deleted one + */ + private fun setLinksWithNodeForSwapping(curNode: RBNode, nodeForSwapping: RBNode) { + nodeForSwapping.leftNode = curNode.leftNode + nodeForSwapping.leftNode?.parent = nodeForSwapping + nodeForSwapping.rightNode = curNode.rightNode + nodeForSwapping.rightNode?.parent = nodeForSwapping + + val parentCurNode = curNode.parent + if (parentCurNode == null) { + nodeForSwapping.parent = null + this.root = nodeForSwapping + } else { + nodeForSwapping.parent = parentCurNode + if (curNode == parentCurNode.leftNode) { + parentCurNode.leftNode = nodeForSwapping + } else { + parentCurNode.rightNode = nodeForSwapping + } + } + } + + /** + * The node that we are moving to the place of the deleted one. + * Therefore, it is necessary to put one of the sons of this peak in its place + * and establish the necessary links. + * + * @param nodeForSwapping the node that we are deleting + * @param sonOfNodeForSwapping the node that will stand in place of the deleted one + * @param sonIsNilNode checking that the son of this vertex is imaginary + */ + private fun setLinksWithSonOfNodeForSwapping( + nodeForSwapping: RBNode, + sonOfNodeForSwapping: RBNode?, + sonIsNilNode: Boolean + ) { + sonOfNodeForSwapping?.parent = nodeForSwapping.parent + + val parentNodeForSwapping = nodeForSwapping.parent + if (parentNodeForSwapping == null) { + sonOfNodeForSwapping?.parent = null + this.root = if (!sonIsNilNode) sonOfNodeForSwapping else null + } else { + if (nodeForSwapping == parentNodeForSwapping.leftNode) { + parentNodeForSwapping.leftNode = sonOfNodeForSwapping + } else { + parentNodeForSwapping.rightNode = sonOfNodeForSwapping + } + } + } + + /** + * Find the node with the next largest key or the node itself if it has a Nil son + * It is an auxiliary function for the delete function + * + * @param curNode the node that we are swapping + */ + private fun , V> getNodeForSwapping(curNode: RBNode): RBNode { + return if (curNode.leftNode == null || curNode.rightNode == null) { + curNode + } else { + // If we got here, then curNode has both a left and a right son + val temp = requireNotNull(curNode.rightNode) { "An attempt to take a non-existent son" } + nodeWithMinKey(temp) + } + } + + /** + * Create an imaginary(Nil) node + * It's filled with some unnecessary data + * + * @param nodeExample some kind of pattern for Nil son + */ + private fun , V> getNilNode(nodeExample: RBNode): RBNode { + val nilSonNodeOfSwapping = RBNode(nodeExample.key, nodeExample.value) + nilSonNodeOfSwapping.color = Color.BLACK + + return nilSonNodeOfSwapping + } + + /** + * Find a node with a minimum key in a tree + * It is an auxiliary function for the delete function + * + * @param node the root of the tree where to find the minimum node + */ + private fun , V> nodeWithMinKey(node: RBNode): RBNode { + var curNode = node + while (curNode.leftNode != null) { + curNode = requireNotNull(curNode.leftNode) { "An attempt to take a non-existent son" } + } + return curNode + } +} diff --git a/lib/src/main/resources/dbConfig.properties b/lib/src/main/resources/dbConfig.properties new file mode 100644 index 0000000..1e31e2d --- /dev/null +++ b/lib/src/main/resources/dbConfig.properties @@ -0,0 +1,5 @@ +neo4j.host = bolt://localhost:7687 +neo4j.username = neo4j +neo4j.password = qwertyui +json.dir = JSONTrees +sql.dbName = SQLTrees \ No newline at end of file diff --git a/lib/src/test/kotlin/avlTree/AVLTreeInvariants.kt b/lib/src/test/kotlin/avlTree/AVLTreeInvariants.kt new file mode 100644 index 0000000..6ef031d --- /dev/null +++ b/lib/src/test/kotlin/avlTree/AVLTreeInvariants.kt @@ -0,0 +1,17 @@ +package avlTree + +import bstrees.model.trees.BSNode +import bstrees.model.trees.avl.AvlNode +import utils.TreesInvariants + +@Suppress("UNCHECKED_CAST") +class AVLTreeInvariants, V, NODE_TYPE : BSNode> : TreesInvariants() { + fun checkAvlTreeInvariants(root: AvlNode?): Boolean = root == null || checkAvlHeightInvariants(root) + && checkNodeInvariants(root as NODE_TYPE) + + private fun checkAvlHeightInvariants(node: AvlNode): Boolean = + ((node.rightNode?.height ?: 0) - (node.leftNode?.height ?: 0) in -1..1) + && (node.leftNode == null || checkAvlHeightInvariants(node.leftNode!!)) + && (node.rightNode == null || checkAvlHeightInvariants(node.rightNode!!)) + +} \ No newline at end of file diff --git a/lib/src/test/kotlin/avlTree/AVLTreeTest.kt b/lib/src/test/kotlin/avlTree/AVLTreeTest.kt new file mode 100644 index 0000000..57ffb09 --- /dev/null +++ b/lib/src/test/kotlin/avlTree/AVLTreeTest.kt @@ -0,0 +1,210 @@ +package avlTree + +import org.junit.jupiter.api.* +import org.junit.jupiter.params.ParameterizedTest +import bstrees.model.trees.avl.AvlNode +import bstrees.model.trees.avl.AvlTree +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.MethodSource +import kotlin.random.Random + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) + +class AVLTreeTest { + + private lateinit var keyValue: List> + private lateinit var bigKeyValue: List> + private val tree = AvlTree() + private val treeChecker = AVLTreeInvariants>() + + @BeforeAll + fun prepareNodes() { + keyValue = List(1000) { Pair(Random.nextInt(5000), Random.nextInt(5000)) }.distinctBy { it.first } + bigKeyValue = List(100000) { Pair(Random.nextInt(500000), Random.nextInt(500000)) }.distinctBy { it.first } + } + + @BeforeEach + fun resetTree() { + tree.root = null + } + + @Test + fun `init null tree`() { + val tree = AvlTree() + Assertions.assertNull(tree.root) { "After initialization, the tree must have NULL root" } + } + + @Test + fun `adding a node`() { + tree.insert(keyValue[0].first, keyValue[0].second) + Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) { "Error adding a node" } + } + + @Test + fun `adding nodes`() { + for (i in keyValue) tree.insert(i.first, i.second) + Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) { "Error adding nodes" } + } + + @Test + fun `adding a lot of nodes`() { + for (i in bigKeyValue) { + tree.insert(i.first, i.second) + } + Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) { "Error adding a lot of nodes" } + } + + @Test + fun `find test`() { + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue.forEach { + Assertions.assertEquals(it.second, tree.find(it.first)) { "Error finding nodes" } + } + } + + @ParameterizedTest(name = "Function get returns correct value for key {0}") + @MethodSource("keyProvider") + fun `find return a correct value`(key: Int) { + keyValue.forEach { tree.insert(it.first, it.second) } + + Assertions.assertEquals(keyValue.find { it.first == key }?.second, tree.find(key)) + + tree.delete(key) + + Assertions.assertEquals(null, tree.find(key)) + } + + companion object { + @JvmStatic + fun keyProvider(): List { + return (0..1000).map { + Arguments.of(Random.nextInt(5000)) + } + } + } + + @Test + fun `adding nodes with equal key`() { + keyValue.forEach { tree.insert(it.first, it.second) } + keyValue.forEach { + tree.insert(it.first, it.second + 1) + Assertions.assertEquals(it.second + 1, tree.find(it.first)) + } + + Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) { "Error adding nodes with equal keys" } + } + + @Test + fun `deleting a part of nodes`(){ + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue = keyValue.shuffled() + + for(i in 0 until keyValue.size){ + tree.delete(keyValue[i].first) + for(j in i + 1 until keyValue.size){ + assertAll("Error deleting a node. The tree must be balanced and must contain all nodes that are not deleted", + { Assertions.assertNotNull(tree.find(keyValue[j].first)) }, + { Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) } + ) + } + } + } + + @Test + fun `deleting a node`() { + tree.insert(keyValue[0].first, keyValue[0].second) + tree.delete(keyValue[0].first) + assertAll("Error deleting a node. The tree must be balanced and must not contain a node after deletion", + { Assertions.assertNull(tree.find(keyValue[0].first)) }, + { Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) } + ) + } + + @Test + fun `deleting nodes`() { + keyValue.forEach { tree.insert(it.first, it.second) } + keyValue.forEach { + tree.delete(it.first) + assertAll("Error deleting nodes. The tree must be balanced and must not contain a node after deletion", + { Assertions.assertNull(tree.find(it.first)) }, + { Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) } + ) + } + } + + @Test + fun `deleting a lot of nodes`() { + bigKeyValue.forEach { tree.insert(it.first, it.second) } + + bigKeyValue = bigKeyValue.shuffled() + bigKeyValue.forEach { tree.delete(it.first) } + + Assertions.assertNull(tree.root) { "Error deleting nodes. The tree must be empty after deleting nodes" } + } + + @Test + fun `find in an empty tree`() { + Assertions.assertNull(tree.find(bigKeyValue[0].first)) { + "Error finding a node which doesn't exist. " + + "It must return null." + } + try { + tree.find(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error finding a node which doesn't exist. " + + "Exception is caught" + } + } + } + + @Test + fun `delete a node which isn't in a tree`() { + + try { + tree.delete(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error deleting a node which doesn't exist. " + + "Exception is caught" + } + } + + Assertions.assertNull(tree.root) { + "Error deleting a node which doesn't exist. " + + "Tree must stay null" + } + } + + @Test + fun `delete a node which isn't in a tree(tree isn't empty)`() { + + for (i in keyValue.indices) { + if (i == 0) continue + tree.insert(keyValue[i].first, keyValue[i].second) + } + + try { + tree.delete(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error deleting nodes which doesn't exist. " + + "Exception is caught" + } + } + + Assertions.assertTrue(treeChecker.checkAvlTreeInvariants(tree.root)) { + "Error deleting nodes which doesn't exist. " + + "Tree invariants aren't executed" + } + + for (i in keyValue.indices) { + if (i == 0) continue + Assertions.assertEquals(keyValue[i].second, tree.find(keyValue[i].first)) + { "Error deleting nodes which doesn't exist. Some of nodes are lost" } + } + + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/balancers/BalancerTest.kt b/lib/src/test/kotlin/balancers/BalancerTest.kt new file mode 100644 index 0000000..f8571ac --- /dev/null +++ b/lib/src/test/kotlin/balancers/BalancerTest.kt @@ -0,0 +1,50 @@ +package balancers + +import bstrees.model.dataBases.converters.utils.ComparableStringConverter +import bstrees.model.dataBases.converters.utils.StringConverter +import bstrees.model.dataBases.converters.utils.createStringConverter +import bstrees.model.trees.randomBinarySearch.RandomBSBalancer +import bstrees.model.trees.randomBinarySearch.RandomBSTree + +import org.junit.jupiter.api.Test +import utils.BSTreeUtil + +@Suppress("UNCHECKED_CAST") +class BalancerTest { + + @Test + fun `left rotate`() { + fun , V> helper(keyStringConverter: ComparableStringConverter, valueStringConverter: StringConverter) { + val balancer = RandomBSBalancer() + + val tree: RandomBSTree = BSTreeUtil.createTree(keyStringConverter, valueStringConverter, "BS") + val newNode = balancer.bsLeftRotate(tree.root!!) + + val leftRotatedTree: RandomBSTree = BSTreeUtil.createLeftRotatedTree(keyStringConverter, valueStringConverter, "BS") + + assert(BSTreeUtil.checkNodeEquals(newNode, leftRotatedTree.root)) + } + helper( + keyStringConverter = createStringConverter("Int"), + valueStringConverter = createStringConverter("Int"), + ) + } + + @Test + fun `right rotate`() { + fun , V> helper(keyStringConverter: ComparableStringConverter, valueStringConverter: StringConverter) { + val balancer = RandomBSBalancer() + + val tree: RandomBSTree = BSTreeUtil.createTree(keyStringConverter, valueStringConverter, "BS") + val newNode = balancer.bsRightRotate(tree.root!!) + + val rightRotatedTree: RandomBSTree = BSTreeUtil.createRightRotatedTree(keyStringConverter, valueStringConverter, "BS") + + assert(BSTreeUtil.checkNodeEquals(newNode, rightRotatedTree.root)) + } + helper( + keyStringConverter = createStringConverter("Int"), + valueStringConverter = createStringConverter("Int"), + ) + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/binarySearchTree/BSTreeInvariants.kt b/lib/src/test/kotlin/binarySearchTree/BSTreeInvariants.kt new file mode 100644 index 0000000..e06435c --- /dev/null +++ b/lib/src/test/kotlin/binarySearchTree/BSTreeInvariants.kt @@ -0,0 +1,18 @@ +package binarySearchTree + +import bstrees.model.trees.BSNode +import bstrees.model.trees.randomBinarySearch.RandomBSNode +import utils.TreesInvariants + +@Suppress("UNCHECKED_CAST") +class BSTreeInvariants, V, NODE_TYPE : BSNode> : TreesInvariants() { + private fun checkBSSizeInvariant(node: RandomBSNode?): Boolean { + return node == null || + node.size == (node.leftNode?.size ?: 0) + (node.rightNode?.size ?: 0) + 1 + && checkBSSizeInvariant(node.leftNode) && checkBSSizeInvariant(node.rightNode) + } + + fun checkBsTreeInvariants(root: RandomBSNode?): Boolean { + return (root == null || checkNodeInvariants(root as NODE_TYPE)) && checkBSSizeInvariant(root) + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/binarySearchTree/RandomBSTreeTest.kt b/lib/src/test/kotlin/binarySearchTree/RandomBSTreeTest.kt new file mode 100644 index 0000000..b2b141f --- /dev/null +++ b/lib/src/test/kotlin/binarySearchTree/RandomBSTreeTest.kt @@ -0,0 +1,213 @@ +package binarySearchTree + +import org.junit.jupiter.api.* +import org.junit.jupiter.params.ParameterizedTest +import bstrees.model.trees.randomBinarySearch.RandomBSNode +import bstrees.model.trees.randomBinarySearch.RandomBSTree +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.MethodSource +import kotlin.random.Random + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) + +class RandomBSTreeTest { + + private lateinit var keyValue: List> + private lateinit var bigKeyValue: List> + private val tree = RandomBSTree() + private val treeChecker = BSTreeInvariants>() + + @BeforeAll + fun prepareNodes() { + keyValue = List(1000) { Pair(Random.nextInt(5000), Random.nextInt(5000)) }.distinctBy { it.first } + bigKeyValue = List(100000) { Pair(Random.nextInt(500000), Random.nextInt(500000)) }.distinctBy { it.first } + } + + @BeforeEach + fun resetTree() { + tree.root = null + } + + @Test + fun `init null tree`() { + val tree = RandomBSTree() + Assertions.assertNull(tree.root) { "After initialization, the tree must have NULL root" } + } + + @Test + fun `adding a node`() { + tree.insert(keyValue[0].first, keyValue[0].second) + Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) { "Error adding a node" } + } + + @Test + fun `adding nodes`() { + for (i in keyValue) tree.insert(i.first, i.second) + Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) { "Error adding nodes" } + } + + @Test + fun `adding a lot of nodes`() { + for (i in bigKeyValue) { + tree.insert(i.first, i.second) + } + Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) { "Error adding a lot of nodes" } + } + + @Test + fun `find test`() { + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue.forEach { + Assertions.assertEquals(it.second, tree.find(it.first)) { "Error finding nodes" } + } + } + + @ParameterizedTest(name = "Function get returns correct value for key {0}") + @MethodSource("keyProvider") + fun `find return a correct value`(key: Int) { + keyValue.forEach { tree.insert(it.first, it.second) } + + Assertions.assertEquals(keyValue.find { it.first == key }?.second, tree.find(key)) + + tree.delete(key) + + Assertions.assertEquals(null, tree.find(key)) + } + + companion object { + @JvmStatic + fun keyProvider(): List { + return (0..1000).map { + Arguments.of(Random.nextInt(5000)) + } + } + } + + @Test + fun `adding nodes with equal key`() { + keyValue.forEach { tree.insert(it.first, it.second) } + keyValue.forEach { + tree.insert(it.first, it.second + 1) + Assertions.assertEquals(it.second + 1, tree.find(it.first)) + } + + Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) { "Error adding nodes with equal keys" } + } + + @Test + fun `deleting a part of nodes`(){ + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue = keyValue.shuffled() + + for(i in 0 until keyValue.size){ + tree.delete(keyValue[i].first) + for(j in i + 1 until keyValue.size){ + assertAll("Error deleting a node. The tree must be balanced and must contain all nodes that are not deleted", + { Assertions.assertNotNull(tree.find(keyValue[j].first)) }, + { Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) } + ) + } + } + } + + @Test + fun `deleting a node`() { + tree.insert(keyValue[0].first, keyValue[0].second) + tree.delete(keyValue[0].first) + assertAll("Error deleting a node. The tree must be balanced and must not contain a node after deletion", + { Assertions.assertNull(tree.find(keyValue[0].first)) }, + { Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) } + ) + } + + @Test + fun `deleting nodes`() { + keyValue.forEach { tree.insert(it.first, it.second) } + keyValue.forEach { + tree.delete(it.first) + assertAll("Error deleting nodes. The tree must be balanced and must not contain a node after deletion", + { Assertions.assertNull(tree.find(it.first)) }, + { Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) } + ) + } + } + + @Test + fun `deleting a lot of nodes`() { + bigKeyValue.forEach { tree.insert(it.first, it.second) } + + bigKeyValue = bigKeyValue.shuffled() + bigKeyValue.forEach { tree.delete(it.first) } + + Assertions.assertNull(tree.root) { "Error deleting nodes. The tree must be empty after deleting nodes" } + } + + @Test + fun `find in an empty tree`() { + + Assertions.assertNull(tree.find(bigKeyValue[0].first)) { + "Error finding a node which doesn't exist. " + + "It must return null." + } + + try { + tree.find(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error finding a node which doesn't exist. " + + "Exception is caught" + } + } + + } + + @Test + fun `delete a node which isn't in a tree`() { + + try { + tree.delete(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error deleting a node which doesn't exist. " + + "Exception is caught" + } + } + + Assertions.assertNull(tree.root) { + "Error deleting a node which doesn't exist. " + + "Tree must stay null" + } + } + + @Test + fun `delete a node which isn't in a tree(tree isn't empty)`() { + + for (i in keyValue.indices) { + if (i == 0) continue + tree.insert(keyValue[i].first, keyValue[i].second) + } + + try { + tree.delete(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error deleting nodes which doesn't exist. " + + "Exception is caught" + } + } + + Assertions.assertTrue(treeChecker.checkBsTreeInvariants(tree.root)) { + "Error deleting nodes which doesn't exist. " + + "Tree invariants aren't executed" + } + + for (i in keyValue.indices) { + if (i == 0) continue + Assertions.assertEquals(keyValue[i].second, tree.find(keyValue[i].first)) + { "Error deleting nodes which doesn't exist. Some of nodes are lost" } + } + + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/converters/TreeToDataConverterTest.kt b/lib/src/test/kotlin/converters/TreeToDataConverterTest.kt new file mode 100644 index 0000000..97f689e --- /dev/null +++ b/lib/src/test/kotlin/converters/TreeToDataConverterTest.kt @@ -0,0 +1,79 @@ +package converters + +import bstrees.model.dataBases.converters.TreeToDataConverter +import bstrees.model.dataBases.converters.treesConverters.AvlToDataConverter +import bstrees.model.dataBases.converters.treesConverters.RandomBsToDataConverter +import bstrees.model.dataBases.converters.treesConverters.RbToDataConverter +import bstrees.model.dataBases.converters.utils.createStringConverter +import bstrees.model.trees.BSNode +import bstrees.model.trees.BSTree +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.MethodSource +import utils.BSTreeUtil +import java.util.stream.Stream + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class TreeToDataConverterTest { + + @ParameterizedTest(name = "serialize deserialize ({0}, {1}) {2}tree") + @MethodSource("keyValueTypeProvider") + fun `serialize deserialize ({0}, {1}) tree`(keyType: String, valueType: String, treeType: String){ + fun , V, NODE_TYPE: BSNode, TREE_TYPE : BSTree> helper(strategy: TreeToDataConverter) { + val tree: TREE_TYPE = BSTreeUtil.createTree(strategy.keyStringConverter, strategy.valueStringConverter, treeType) + + val dataTree = strategy.serializeTree(tree, "") + + val resultTree = strategy.deserializeTree(dataTree) + + Assertions.assertTrue(BSTreeUtil.checkNodeEquals(tree.root, resultTree.root), "Serialize deserialize (${keyType}, ${valueType}) ${treeType}tree test error") + } + helper(createStrategy(treeType, keyType, valueType)) + } + + + companion object { + @JvmStatic + fun keyValueTypeProvider(): Stream { + return Stream.of( + Arguments.of("String", "String", "BS"), + Arguments.of("String", "Int", "BS"), + Arguments.of("Int", "String", "BS"), + Arguments.of("String", "String", "BS"), + Arguments.of("String", "String", "AVL"), + Arguments.of("String", "Int", "AVL"), + Arguments.of("Int", "String", "AVL"), + Arguments.of("String", "String", "AVL"), + Arguments.of("String", "String", "RB"), + Arguments.of("String", "Int", "RB"), + Arguments.of("Int", "String", "RB"), + Arguments.of("String", "String", "RB") + ) + } + } + + private fun createStrategy(treeType: String, keyType: String, valueType: String): TreeToDataConverter<*, *, *, *, *> = when (treeType) { + "AVL" -> AvlToDataConverter( + keyStringConverter = createStringConverter(keyType), + valueStringConverter = createStringConverter(valueType), + keyType = keyType, + valueType = valueType + ) + "RB" -> RbToDataConverter( + keyStringConverter = createStringConverter(keyType), + valueStringConverter = createStringConverter(valueType), + keyType = keyType, + valueType = valueType + ) + "BS" -> RandomBsToDataConverter( + keyStringConverter = createStringConverter(keyType), + valueStringConverter = createStringConverter(valueType), + keyType = keyType, + valueType = valueType + ) + else -> throw IllegalArgumentException("Unknown tree type $treeType") + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/dataBases/JsonTreeRepoTest.kt b/lib/src/test/kotlin/dataBases/JsonTreeRepoTest.kt new file mode 100644 index 0000000..d65bf65 --- /dev/null +++ b/lib/src/test/kotlin/dataBases/JsonTreeRepoTest.kt @@ -0,0 +1,111 @@ +package dataBases + + +import bstrees.model.dataBases.reps.JsonTreeRepo +import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import utils.TreeDataUtil +import java.nio.file.Files +import kotlin.io.path.Path + +const val DIR = "JsonTreeRepo" + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class JsonTreeRepoTest { + + private val repo = JsonTreeRepo(DIR) + + @Test + fun `setting and getting unique tree`(){ + val dataTree = TreeDataUtil.getTreeData("first", "BS") + repo.setTree(dataTree) + + val resultDataTree = repo.getTree("first", "BS") + + Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree, resultDataTree), "error setting unique tree") + } + + @Test + fun `setting and getting trees with the same names and types`(){ + val dataTree1 = TreeDataUtil.getTreeData("name", "RB") + val dataTree2 = TreeDataUtil.getTreeData("name", "RB") + + repo.setTree(dataTree1) + val resultDataTree1 = repo.getTree("name", "RB") + + repo.setTree(dataTree2) + val resultDataTree2 = repo.getTree("name", "RB") + + Assertions.assertAll("Error setting trees with the same name", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree2, resultDataTree2)) } + ) + } + + @Test + fun `setting and getting trees with the same names but different types`(){ + val dataTree1 = TreeDataUtil.getTreeData("name2", "BS") + val dataTree2 = TreeDataUtil.getTreeData("name2", "RB") + + repo.setTree(dataTree1) + repo.setTree(dataTree2) + + val resultDataTree1 = repo.getTree("name2", "BS") + val resultDataTree2 = repo.getTree("name2", "RB") + + Assertions.assertAll("Error setting trees with the same name but different types", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree2, resultDataTree2)) } + ) + } + + @Test + fun `setting and getting trees with different names but the same types`(){ + val dataTree1 = TreeDataUtil.getTreeData("name3", "AVL") + val dataTree2 = TreeDataUtil.getTreeData("name4", "AVL") + + repo.setTree(dataTree1) + repo.setTree(dataTree2) + + val resultDataTree1 = repo.getTree("name3", "AVL") + val resultDataTree2 = repo.getTree("name4", "AVL") + + Assertions.assertAll("Error setting trees with different names but the same types", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree2, resultDataTree2)) } + ) + } + + @Test + fun `getting non-existent tree`(){ + val resultDataTree = repo.getTree("name5", "RB") + + Assertions.assertNull(resultDataTree, "error getting non-existent tree") + } + + @Test + fun `deleting tree`(){ + val dataTree1 = TreeDataUtil.getTreeData("name6", "RB") + + repo.setTree(dataTree1) + val resultDataTree1 = repo.getTree("name6", "RB") + + repo.deleteTree("name6", "RB") + val resultDataTree2 = repo.getTree("name6", "RB") + + Assertions.assertAll("Error deleting tree", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertNull(resultDataTree2) } + ) + } + + @AfterAll + fun `delete dir`(){ + Files.walk(Path(DIR)) + .sorted(Comparator.reverseOrder()) + .map { it.toFile() } + .forEach { it.delete() } + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/dataBases/SQLTreeRepoTest.kt b/lib/src/test/kotlin/dataBases/SQLTreeRepoTest.kt new file mode 100644 index 0000000..920c179 --- /dev/null +++ b/lib/src/test/kotlin/dataBases/SQLTreeRepoTest.kt @@ -0,0 +1,109 @@ +package dataBases + +import bstrees.model.dataBases.reps.SQLTreeRepo +import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import utils.TreeDataUtil +import java.nio.file.Files +import kotlin.io.path.Path + +const val DB_NAME = "SQLTreeRepo" + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class SQLTreeRepoTest { + private val repo = SQLTreeRepo(DB_NAME) + + @Test + fun `setting and getting unique tree`(){ + val dataTree = TreeDataUtil.getTreeData("first", "BS") + repo.setTree(dataTree) + + val resultDataTree = repo.getTree("first", "BS") + + Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree, resultDataTree), "error setting unique tree") + } + + @Test + fun `setting and getting trees with the same names and types`(){ + val dataTree1 = TreeDataUtil.getTreeData("name", "RB") + val dataTree2 = TreeDataUtil.getTreeData("name", "RB") + + repo.setTree(dataTree1) + val resultDataTree1 = repo.getTree("name", "RB") + + repo.setTree(dataTree2) + val resultDataTree2 = repo.getTree("name", "RB") + + Assertions.assertAll("Error setting trees with the same name", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree2, resultDataTree2)) } + ) + } + + @Test + fun `setting and getting trees with the same names but different types`(){ + val dataTree1 = TreeDataUtil.getTreeData("name2", "BS") + val dataTree2 = TreeDataUtil.getTreeData("name2", "RB") + + repo.setTree(dataTree1) + repo.setTree(dataTree2) + + val resultDataTree1 = repo.getTree("name2", "BS") + val resultDataTree2 = repo.getTree("name2", "RB") + + Assertions.assertAll("Error setting trees with the same name but different types", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree2, resultDataTree2)) } + ) + } + + @Test + fun `setting and getting trees with different names but the same types`(){ + val dataTree1 = TreeDataUtil.getTreeData("name3", "AVL") + val dataTree2 = TreeDataUtil.getTreeData("name4", "AVL") + + repo.setTree(dataTree1) + repo.setTree(dataTree2) + + val resultDataTree1 = repo.getTree("name3", "AVL") + val resultDataTree2 = repo.getTree("name4", "AVL") + + Assertions.assertAll("Error setting trees with different names but the same types", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree2, resultDataTree2)) } + ) + } + + @Test + fun `getting non-existent tree`(){ + val resultDataTree = repo.getTree("name5", "RB") + + Assertions.assertNull(resultDataTree, "error getting non-existent tree") + } + + @Test + fun `deleting tree`(){ + val dataTree1 = TreeDataUtil.getTreeData("name6", "RB") + + repo.setTree(dataTree1) + val resultDataTree1 = repo.getTree("name6", "RB") + + repo.deleteTree("name6", "RB") + val resultDataTree2 = repo.getTree("name6", "RB") + + Assertions.assertAll("Error deleting tree", + { Assertions.assertTrue(TreeDataUtil.isEqualsTrees(dataTree1, resultDataTree1)) }, + { Assertions.assertNull(resultDataTree2) } + ) + } + + @AfterAll + fun `delete DB`(){ + Files.walk(Path(DB_NAME)) + .sorted(Comparator.reverseOrder()) + .map { it.toFile() } + .forEach { it.delete() } + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/redBlackTree/RBTreeInvariants.kt b/lib/src/test/kotlin/redBlackTree/RBTreeInvariants.kt new file mode 100644 index 0000000..b8f51c5 --- /dev/null +++ b/lib/src/test/kotlin/redBlackTree/RBTreeInvariants.kt @@ -0,0 +1,53 @@ +package redBlackTree + +import bstrees.model.trees.BSNode +import bstrees.model.trees.redBlack.RBNode +import utils.TreesInvariants + +@Suppress("UNCHECKED_CAST") +class RBTreeInvariants, V, NODE_TYPE : BSNode> : TreesInvariants() { + fun checkRBTreeInvariants(root: RBNode?): Boolean { + return root == null || root.parent == null && checkNodeInvariants(root as NODE_TYPE) && root.color == RBNode.Color.BLACK && + checkRBNodeBlackHeightInvariant(root, 0, getBlackHeightExample(root)) && + checkRBNodeBlackParentForRedInvariant(root) + } + + private fun checkRBNodeBlackParentForRedInvariant(node: RBNode): Boolean { + return (node.color == RBNode.Color.BLACK || node.parent!!.color == RBNode.Color.BLACK) && + (node.leftNode == null || checkRBNodeBlackParentForRedInvariant(node.leftNode!!)) && + (node.rightNode == null || checkRBNodeBlackParentForRedInvariant(node.rightNode!!)) + } + + private fun checkRBNodeBlackHeightInvariant(node: RBNode, curHeight: Int, rightHeight: Int): Boolean { + val newCurHeight = curHeight + if (node.color == RBNode.Color.BLACK) 1 else 0 + if (node.leftNode == null && node.rightNode == null) { + return newCurHeight == rightHeight + } + return ((node.leftNode == null || checkRBNodeBlackHeightInvariant( + node.leftNode!!, + newCurHeight, + rightHeight + )) && + (node.rightNode == null || checkRBNodeBlackHeightInvariant( + node.rightNode!!, + newCurHeight, + rightHeight + ))) + } + + /** + * We take the height of the leftmost leaf in order to compare it + * with the heights to other leaves of the tree + */ + private fun getBlackHeightExample(root: RBNode): Int { + var curNode: RBNode? = root + var blackHeight = 0 + while (curNode != null) { + if (curNode.color == RBNode.Color.BLACK) { + ++blackHeight + } + curNode = curNode.leftNode + } + return blackHeight + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/redBlackTree/RBTreeTest.kt b/lib/src/test/kotlin/redBlackTree/RBTreeTest.kt new file mode 100644 index 0000000..3675880 --- /dev/null +++ b/lib/src/test/kotlin/redBlackTree/RBTreeTest.kt @@ -0,0 +1,225 @@ +package redBlackTree + +import org.junit.jupiter.api.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.params.ParameterizedTest +import bstrees.model.trees.redBlack.RBNode +import bstrees.model.trees.redBlack.RBTree +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.MethodSource +import kotlin.random.Random + +const val seed = 10 + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) + +class RBTreeTest { + + private val randomizer = Random(seed) + + private lateinit var keyValue: List> + private lateinit var bigKeyValue: List> + private val tree = RBTree() + private val treeChecker = RBTreeInvariants>() + + + @BeforeAll + fun prepareNodes() { + keyValue = List(1000) { Pair(randomizer.nextInt(5000), randomizer.nextInt(5000)) }.distinctBy { it.first } + bigKeyValue = + List(100000) { Pair(randomizer.nextInt(500000), randomizer.nextInt(500000)) }.distinctBy { it.first } + } + + @BeforeEach + fun resetTree() { + tree.root = null + } + + @Test + fun `init null tree`() { + val tree = RBTree() + assertEquals(null, tree.root) { "After initialization, the tree must have NULL root" } + } + + @Test + fun `adding a node`() { + tree.insert(keyValue[0].first, keyValue[0].second) + Assertions.assertTrue(treeChecker.checkRBTreeInvariants(tree.root)) { "Error adding a node" } + } + + @Test + fun `adding nodes`() { + keyValue.forEach { + tree.insert(it.first, it.second) + + assert(treeChecker.checkRBTreeInvariants(tree.root)) { "Error adding nodes" } + } + } + + @Test + fun `adding nodes with equal key`() { + keyValue.forEach { tree.insert(it.first, it.second) } + keyValue.forEach { + tree.insert(it.first, it.second + 1) + assertEquals(it.second + 1, tree.find(it.first)) + } + + Assertions.assertTrue(treeChecker.checkRBTreeInvariants(tree.root)) { "Error adding nodes with equal keys" } + } + + @Test + fun `deleting a part of nodes`(){ + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue = keyValue.shuffled() + + for(i in 0 until keyValue.size){ + tree.delete(keyValue[i].first) + for(j in i + 1 until keyValue.size){ + assertAll("Error deleting a node. The tree must be balanced and must contain all nodes that are not deleted", + { Assertions.assertNotNull(tree.find(keyValue[j].first)) }, + { Assertions.assertTrue(treeChecker.checkRBTreeInvariants(tree.root)) } + ) + } + } + } + + @Test + fun `adding a lot of nodes`() { + val bigTree = RBTree() + + bigKeyValue.forEach { bigTree.insert(it.first, it.second) } + + assert(treeChecker.checkRBTreeInvariants(bigTree.root)) { "Error adding a lot of nodes" } + } + + @Test + fun `find test`() { + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue.forEach { + assertEquals(it.second, tree.find(it.first)) { "Error finding nodes" } + } + } + + @ParameterizedTest(name = "Function get returns correct value for key {0}") + @MethodSource("keyProvider") + fun `find return a correct value`(key: Int) { + keyValue.forEach { tree.insert(it.first, it.second) } + + assertEquals(keyValue.find { it.first == key }?.second, tree.find(key)) + + tree.delete(key) + + assertEquals(null, tree.find(key)) + } + + companion object { + @JvmStatic + fun keyProvider(): List { + return (0..1000).map { + Arguments.of(Random.nextInt(5000)) + } + } + } + + @Test + fun `deleting a node`() { + tree.insert(keyValue[0].first, keyValue[0].second) + tree.delete(keyValue[0].first) + assertAll("Error deleting a node. The tree must be balanced and must not contain a node after deletion", + { Assertions.assertNull(tree.find(keyValue[0].first)) }, + { Assertions.assertTrue(treeChecker.checkRBTreeInvariants(tree.root)) } + ) + } + + @Test + fun `deleting nodes`() { + keyValue.forEach { tree.insert(it.first, it.second) } + + keyValue.forEach { + tree.delete(it.first) + + assertAll("Error deleting nodes. The tree must be balanced and must not contain a node after deletion", + { assertEquals(null, tree.find(it.first)) }, + { assert(treeChecker.checkRBTreeInvariants(tree.root)) } + ) + } + } + + @Test + fun `deleting a lot of nodes`() { + val bigTree = RBTree() + bigKeyValue.forEach { bigTree.insert(it.first, it.second) } + + bigKeyValue = bigKeyValue.shuffled() + bigKeyValue.forEach { bigTree.delete(it.first) } + + assertEquals(null, bigTree.root) { "Error deleting nodes. The tree must be empty after deleting nodes" } + } + + + @Test + fun `find in an empty tree`() { + Assertions.assertNull(tree.find(bigKeyValue[0].first)) { + "Error finding a node which doesn't exist. " + + "It must return null." + } + try { + tree.find(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error finding a node which doesn't exist. " + + "Exception is caught" + } + } + } + + @Test + fun `delete a node which isn't in a tree`() { + + try { + tree.delete(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error deleting a node which doesn't exist. " + + "Exception is caught" + } + } + + Assertions.assertNull(tree.root) { + "Error deleting a node which doesn't exist. " + + "Tree must stay null" + } + } + + @Test + fun `delete a node which isn't in a tree(tree isn't empty)`() { + + for (i in keyValue.indices) { + if (i == 0) continue + tree.insert(keyValue[i].first, keyValue[i].second) + } + + try { + tree.delete(bigKeyValue[0].first) + } catch (e: Exception) { + Assertions.assertTrue(false) { + "Error deleting nodes which doesn't exist. " + + "Exception is caught" + } + } + + Assertions.assertTrue(treeChecker.checkRBTreeInvariants(tree.root)) { + "Error deleting nodes which doesn't exist. " + + "Tree invariants aren't executed" + } + + for (i in keyValue.indices) { + if (i == 0) continue + assertEquals(keyValue[i].second, tree.find(keyValue[i].first)) + { "Error deleting nodes which doesn't exist. Some of nodes are lost" } + } + + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/utils/BSTreeUtil.kt b/lib/src/test/kotlin/utils/BSTreeUtil.kt new file mode 100644 index 0000000..bff7834 --- /dev/null +++ b/lib/src/test/kotlin/utils/BSTreeUtil.kt @@ -0,0 +1,208 @@ +package utils + +import bstrees.model.dataBases.converters.utils.ComparableStringConverter +import bstrees.model.dataBases.converters.utils.StringConverter +import bstrees.model.trees.BSNode +import bstrees.model.trees.BSTree +import bstrees.model.trees.avl.AvlNode +import bstrees.model.trees.avl.AvlTree +import bstrees.model.trees.randomBinarySearch.RandomBSNode +import bstrees.model.trees.randomBinarySearch.RandomBSTree +import bstrees.model.trees.redBlack.RBNode +import bstrees.model.trees.redBlack.RBTree + +/** + * BSTreeUtil performs the BSTree handler function for test classes + */ +@Suppress("UNCHECKED_CAST") +object BSTreeUtil { + + fun , V, NODE_TYPE : BSNode> checkNodeEquals( + root1: NODE_TYPE?, + root2: NODE_TYPE? + ): Boolean { + if (root1 == null || root2 == null) { + return root1 == null && root2 == null + } + return root1.key == root2.key && root1.value == root2.value && + checkNodeEquals(root1.leftNode, root2.leftNode) && + checkNodeEquals(root1.rightNode, root2.rightNode) + } + + private fun , V, TREE_TYPE : BSTree> getTreeInstance(treeType: String): TREE_TYPE { + return when (treeType) { + "AVL" -> AvlTree() as TREE_TYPE + "RB" -> RBTree() as TREE_TYPE + "BS" -> RandomBSTree() as TREE_TYPE + else -> throw IllegalArgumentException("Unknown tree type $treeType") + } + } + + private fun , V, NODE_TYPE> getNodeInstance(treeType: String, key: K, value: V): NODE_TYPE { + return when (treeType) { + "AVL" -> AvlNode(key, value) as NODE_TYPE + "RB" -> RBNode(key, value) as NODE_TYPE + "BS" -> RandomBSNode(key, value) as NODE_TYPE + else -> throw IllegalArgumentException("Unknown tree type $treeType") + } + } + + fun , V, NODE_TYPE : BSNode, TREE_TYPE : BSTree> createTree( + keyStringConverter: ComparableStringConverter, + valueStringConverter: StringConverter, + treeType: String + ): TREE_TYPE { + val tree: TREE_TYPE = getTreeInstance(treeType) + tree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("0"), + valueStringConverter.fromString("0") + ) + val testRBTreeRoot = tree.root!! + + val leftSubTestRBTree: TREE_TYPE = getTreeInstance(treeType) + leftSubTestRBTree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("-2"), + valueStringConverter.fromString("2") + ) + val leftSubTestRBTreeRoot = leftSubTestRBTree.root!! + leftSubTestRBTreeRoot.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("-3"), + valueStringConverter.fromString("5") + ) + leftSubTestRBTreeRoot.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("-1"), + valueStringConverter.fromString("6") + ) + + val rightSubTestRBTree: TREE_TYPE = getTreeInstance(treeType) + rightSubTestRBTree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("2"), + valueStringConverter.fromString("3") + ) + val rightSubTestRBTreeRoot = rightSubTestRBTree.root!! + rightSubTestRBTreeRoot.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("1"), + valueStringConverter.fromString("7") + ) + rightSubTestRBTreeRoot.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("3"), + valueStringConverter.fromString("8") + ) + + testRBTreeRoot.leftNode = leftSubTestRBTreeRoot + testRBTreeRoot.rightNode = rightSubTestRBTreeRoot + + return tree + } + + fun , V, NODE_TYPE : BSNode, TREE_TYPE : BSTree> createLeftRotatedTree( + keyStringConverter: ComparableStringConverter, + valueStringConverter: StringConverter, + treeType: String + ): TREE_TYPE { + val leftRotatedTestRandomBSTree: TREE_TYPE = getTreeInstance(treeType) + leftRotatedTestRandomBSTree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("2"), + valueStringConverter.fromString("3") + ) + val leftRotatedTestBSTreeRoot = leftRotatedTestRandomBSTree.root!! + + leftRotatedTestBSTreeRoot.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("3"), + valueStringConverter.fromString("8") + ) + leftRotatedTestBSTreeRoot.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("0"), + valueStringConverter.fromString("0") + ) + + val leftRotatedSubTestRandomBSTree: TREE_TYPE = getTreeInstance(treeType) + leftRotatedSubTestRandomBSTree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("-2"), + valueStringConverter.fromString("2") + ) + val leftRotatedSubTestBSTreeRoot = leftRotatedSubTestRandomBSTree.root!! + leftRotatedSubTestBSTreeRoot.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("-3"), + valueStringConverter.fromString("5") + ) + leftRotatedSubTestBSTreeRoot.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("-1"), + valueStringConverter.fromString("6") + ) + + leftRotatedTestBSTreeRoot.leftNode?.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("1"), + valueStringConverter.fromString("7") + ) + leftRotatedTestBSTreeRoot.leftNode?.leftNode = leftRotatedSubTestBSTreeRoot + + return leftRotatedTestRandomBSTree + } + + fun , V, NODE_TYPE : BSNode, TREE_TYPE : BSTree> createRightRotatedTree( + keyStringConverter: ComparableStringConverter, + valueStringConverter: StringConverter, + treeType: String + ): TREE_TYPE { + val rightRotatedTestRandomBSTree: TREE_TYPE = getTreeInstance(treeType) + rightRotatedTestRandomBSTree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("-2"), + valueStringConverter.fromString("2") + ) + val rightRotatedTestBSTreeRoot = rightRotatedTestRandomBSTree.root!! + + rightRotatedTestBSTreeRoot.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("-3"), + valueStringConverter.fromString("5") + ) + rightRotatedTestBSTreeRoot.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("0"), + valueStringConverter.fromString("0") + ) + + val rightRotatedSubTestRandomBSTree: TREE_TYPE = getTreeInstance(treeType) + rightRotatedSubTestRandomBSTree.root = getNodeInstance( + treeType, + keyStringConverter.fromString("2"), + valueStringConverter.fromString("3") + ) + val rightRotatedSubTestBSTreeRoot = rightRotatedSubTestRandomBSTree.root!! + rightRotatedSubTestBSTreeRoot.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("1"), + valueStringConverter.fromString("7") + ) + rightRotatedSubTestBSTreeRoot.rightNode = getNodeInstance( + treeType, + keyStringConverter.fromString("3"), + valueStringConverter.fromString("8") + ) + + rightRotatedTestBSTreeRoot.rightNode?.leftNode = getNodeInstance( + treeType, + keyStringConverter.fromString("-1"), + valueStringConverter.fromString("6") + ) + rightRotatedTestBSTreeRoot.rightNode?.rightNode = rightRotatedSubTestBSTreeRoot + + return rightRotatedTestRandomBSTree + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/utils/TreeDataUtil.kt b/lib/src/test/kotlin/utils/TreeDataUtil.kt new file mode 100644 index 0000000..392fdf9 --- /dev/null +++ b/lib/src/test/kotlin/utils/TreeDataUtil.kt @@ -0,0 +1,90 @@ +package utils + +import bstrees.model.dataBases.NodeData +import bstrees.model.dataBases.TreeData + +object TreeDataUtil { + fun getTreeData(name: String, treeType: String): TreeData { + return TreeData( + name = name, + treeType = treeType, + keyType = "", + valueType = "", + NodeData( + "1", + "", + "", + 0, + 0, + NodeData( + "2", + "", + "", + 0, + 0, + NodeData( + "3", + "", + "", + 0, + 0, + null, + null + ), + NodeData( + "4", + "", + "", + 0, + 0, + null, + null + ) + ), + NodeData( + "5", + "", + "", + 0, + 0, + NodeData( + "6", + "", + "", + 0, + 0, + null, + null + ), + NodeData( + "7", + "", + "", + 0, + 0, + null, + null + ) + ) + ) + ) + } + + fun isEqualsTrees(tree1: TreeData?, tree2: TreeData?): Boolean{ + if(tree1 == null && tree2 == null)return true + if(tree1 == null || tree2 == null)return false + return tree1.name == tree2.name && tree1.treeType == tree2.treeType && + tree1.keyType == tree2.keyType && tree1.valueType == tree2.valueType && + isEqualsNodes(tree1.root, tree2.root) + } + + private fun isEqualsNodes(node1: NodeData?, node2: NodeData?): Boolean{ + if(node1 == null && node2 == null)return true + if(node1 == null || node2 == null)return false + return node1.key == node2.key && node1.value == node2.value && + node1.metadata == node2.metadata && + node1.posX == node2.posX && node1.posY == node2.posY && + isEqualsNodes(node1.leftNode, node2.leftNode) && + isEqualsNodes(node1.rightNode, node2.rightNode) + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/utils/TreesInvariants.kt b/lib/src/test/kotlin/utils/TreesInvariants.kt new file mode 100644 index 0000000..457ff31 --- /dev/null +++ b/lib/src/test/kotlin/utils/TreesInvariants.kt @@ -0,0 +1,12 @@ +package utils + +import bstrees.model.trees.BSNode + +open class TreesInvariants, V, NODE_TYPE : BSNode> { + protected fun checkNodeInvariants(node: NODE_TYPE): Boolean { + return (node.leftNode == null || node.leftNode!!.parent == node && + node.leftNode!!.key < node.key && checkNodeInvariants(node.leftNode!!)) && + (node.rightNode == null || node.rightNode!!.parent == node && + node.rightNode!!.key > node.key && checkNodeInvariants(node.rightNode!!)) + } +} \ No newline at end of file diff --git a/neo4j_up.sh b/neo4j_up.sh new file mode 100755 index 0000000..dbf552b --- /dev/null +++ b/neo4j_up.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +BASEDIR=$(realpath "$(dirname "$0")") + +. "${BASEDIR}/CONTAINER.conf" + +docker run \ + --rm \ + --name "$CONTAINER_NAME" \ + --publish=7474:7474 --publish=7687:7687 \ + --env NEO4J_AUTH=neo4j/"$PASSWORD" \ + neo4j:latest diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..d4d88e1 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,3 @@ +rootProject.name = "trees-6" +include("app") +include("lib")