From 95c2f8c02a68163619ffadbb9bfeecaa6097d39e Mon Sep 17 00:00:00 2001 From: norangebit Date: Wed, 17 Apr 2019 22:49:09 +0200 Subject: [PATCH] add basic implementation of BST --- .../datastructures/dictionary/Dictionaries.kt | 4 + .../datastructures/dictionary/ImmutableBST.kt | 200 ++++++++++++++++++ .../dictionary/ImmutableBSTTest.kt | 180 ++++++++++++++++ 3 files changed, 384 insertions(+) create mode 100644 src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBST.kt create mode 100644 src/test/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBSTTest.kt diff --git a/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/Dictionaries.kt b/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/Dictionaries.kt index e36e98a..3a3674a 100644 --- a/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/Dictionaries.kt +++ b/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/Dictionaries.kt @@ -41,4 +41,8 @@ interface OrderedDictionary, V> : Dictionary { fun min(): Option fun floor(key: K): Option fun ceiling(key: K): Option + fun select(pos: Int): Option + fun preOrder(transform: (K) -> R) + fun inOrder(transform: (K) -> R) + fun postOrder(transform: (K) -> R) } diff --git a/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBST.kt b/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBST.kt new file mode 100644 index 0000000..269e696 --- /dev/null +++ b/src/main/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBST.kt @@ -0,0 +1,200 @@ +/* + * MIT License + * + * Copyright (c) 2019 norangebit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package it.norangeb.algorithms.datastructures.dictionary + +import arrow.core.None +import arrow.core.Option +import arrow.core.Some +import arrow.core.toOption + +class ImmutableBST, V> : OrderedDictionary { + private var root: Option> = None + + override fun get(key: K): Option = get(root, key).map { it.value } + + private fun get(node: Option>, key: K): Option> = node + .flatMap { + when { + it.key == key -> it.toOption() + key > it.key -> get(it.right, key) + else -> get(it.left, key) + } + } + + override fun set(key: K, value: V) { + root = set(root, key, value) + } + + private fun set( + node: Option>, + key: K, value: V + ): Option> = node.fold( + { Node(key, value) }, + { + when { + key == it.key -> it.clone(value = value) + key > it.key -> it.clone(right = set(it.right, key, value)) + else -> it.clone(left = set(it.left, key, value)) + } + } + ).toOption() + + override fun delete(key: K) { + root = delete(root, key) + } + + private fun delete( + node: Option>, + key: K + ): Option> = node.flatMap { deleteNode(it, key) } + + private fun deleteNode( + node: Node, + key: K + ): Option> = when { + node.key == key -> when { + node.left is None && node.right is None -> None + node.left is None -> node.right + node.right is None -> node.left + else -> node.right.map { deleteNodeWithTwoChild(node, it) } + } + + key > node.key -> node.clone( + right = delete(node.right, key) + ).toOption() + + else -> node.clone(left = delete(node.left, key)).toOption() + } + + private fun deleteNodeWithTwoChild( + father: Node, + rightChild: Node + ): Node { + val replacement = down(rightChild) { left } + return replacement + .clone( + left = father.left, + right = delete(rightChild.toOption(), replacement.key) + ) + } + + override fun contains(key: K): Boolean = get(root, key) is Some + + override fun isEmpty(): Boolean = root is None + + override fun size(): Int = size(root) + + private fun size(node: Option>) = node.fold( + { 0 }, + { it.child + 1 } + ) + + override fun max(): Option = root.map { + down(it) { right }.key + } + + override fun min(): Option = root.map { + down(it) { left }.key + } + + private fun down( + node: Node, + side: Node.() -> Option> + ): Node = side(node) + .fold({ node }, { down(it, side) }) + + override fun select(pos: Int): Option = select(root, pos) + + private fun select( + node: Option>, + pos: Int + ): Option = + node.flatMap { + val leftChild = size(it.left) + when { + leftChild > pos -> select(it.left, pos) + leftChild < pos -> select(it.right, pos - leftChild - 1) + else -> it.key.toOption() + } + } + + override fun floor(key: K): Option { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun ceiling(key: K): Option { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun inOrder(transform: (K) -> R) = inOrder(root, transform) + + private fun inOrder(node: Option>, action: (K) -> R) { + node.map { + inOrder(it.left, action) + action(it.key) + inOrder(it.right, action) + } + } + + override fun postOrder(transform: (K) -> R) = postOrder(root, transform) + + private fun postOrder(node: Option>, action: (K) -> R) { + node.map { + postOrder(it.left, action) + postOrder(it.right, action) + action(it.key) + } + } + + override fun preOrder(transform: (K) -> R) = preOrder(root, transform) + + private fun preOrder(node: Option>, action: (K) -> R) { + node.map { + action(it.key) + preOrder(it.left, action) + preOrder(it.right, action) + } + } + + data class Node, V>( + val key: K, + val value: V, + val left: Option> = None, + val right: Option> = None, + val child: Int = 0 + ) { + fun clone( + key: K = this.key, + value: V = this.value, + left: Option> = this.left, + right: Option> = this.right + ): Node { + val leftChild = left.fold({ 0 }, { it.child + 1 }) + val rightChild = right.fold({ 0 }, { it.child + 1 }) + return Node(key, value, left, right, leftChild + rightChild) + } + } +} \ No newline at end of file diff --git a/src/test/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBSTTest.kt b/src/test/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBSTTest.kt new file mode 100644 index 0000000..1634d3f --- /dev/null +++ b/src/test/kotlin/it/norangeb/algorithms/datastructures/dictionary/ImmutableBSTTest.kt @@ -0,0 +1,180 @@ +/* + * MIT License + * + * Copyright (c) 2019 norangebit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package it.norangeb.algorithms.datastructures.dictionary + +import arrow.core.None +import arrow.core.Some +import org.amshove.kluent.`should be equal to` +import org.amshove.kluent.`should be` +import org.amshove.kluent.should +import org.amshove.kluent.shouldEqual +import org.junit.jupiter.api.Test + + +class ImmutableBSTTest { + + @Test + fun test() { + val orderedMap: OrderedDictionary = ImmutableBST() + orderedMap.isEmpty() `should be` true + orderedMap.size() `should be equal to` 0 + orderedMap.contains("UNO") `should be` false + orderedMap.max() `should be` None + orderedMap.min() `should be` None + + orderedMap["QUATTRO"] = 4 + orderedMap["UNO"] = 0 + + orderedMap.contains("UNO") `should be` true + + orderedMap["TRE"] = 3 + orderedMap["UNO"] = 1 + + orderedMap.size() `should be equal to` 3 + orderedMap["UNO"] should { this == Some(1) } + + orderedMap["DUE"] = 2 + + orderedMap["DUE"] should { this == Some(2) } + orderedMap.max() should { this == Some("UNO") } + orderedMap.min() should { this == Some("DUE") } + } + + @Test + fun testDelete() { + val orderedMap: OrderedDictionary = ImmutableBST() + + orderedMap[7] = "sette" + orderedMap[2] = "due" + orderedMap[3] = "tre" + orderedMap[10] = "dieci" + orderedMap[1] = "uno" + orderedMap[8] = "otto" + orderedMap[13] = "tredici" + orderedMap[5] = "cinque" + orderedMap[11] = "undici" + + orderedMap.size() `should be equal to` 9 + + // delete absent key + orderedMap.delete(0) + + orderedMap.size() `should be equal to` 9 + + //delete node with no child + orderedMap.delete(1) + + orderedMap.size() `should be equal to` 8 + orderedMap.min() should { this == Some(2) } + + //delete node with only right child + orderedMap.delete(2) + + orderedMap.size() `should be equal to` 7 + orderedMap.min() should { this == Some(3) } + + //delete node with two child + orderedMap.delete(10) + + orderedMap.size() `should be equal to` 6 + + orderedMap.delete(13) + //delete node with only left child + orderedMap.delete(11) + + orderedMap.size() `should be equal to` 4 + orderedMap.max() should { this == Some(8) } + } + + @Test + fun testOrderedOperation() { + val orderedMap: OrderedDictionary = ImmutableBST() + + orderedMap.select(0) `should be` None + + orderedMap[9] = 9 + orderedMap[4] = 4 + orderedMap[14] = 14 + + orderedMap.select(0) should { this == Some(4) } + orderedMap.select(1) should { this == Some(9) } + orderedMap.select(2) should { this == Some(14) } + orderedMap.select(3) `should be` None + + orderedMap[13] = 13 + orderedMap[15] = 15 + orderedMap[3] = 3 + orderedMap[5] = 5 + orderedMap[2] = 2 + orderedMap[6] = 6 + orderedMap[12] = 12 + orderedMap[16] = 16 + orderedMap[1] = 1 + + orderedMap.select(0) shouldEqual orderedMap.min() + orderedMap.select(11) shouldEqual orderedMap.max() + + orderedMap[0] = 0 + orderedMap[11] = 11 + orderedMap[10] = 10 + orderedMap[17] = 17 + orderedMap[18] = 18 + orderedMap[7] = 7 + orderedMap[8] = 8 + + orderedMap.select(-1) `should be` None + orderedMap.select(0) should { this == Some(0) } + orderedMap.select(1) should { this == Some(1) } + orderedMap.select(5) should { this == Some(5) } + orderedMap.select(8) should { this == Some(8) } + orderedMap.select(9) should { this == Some(9) } + orderedMap.select(10) should { this == Some(10) } + orderedMap.select(14) should { this == Some(14) } + orderedMap.select(17) should { this == Some(17) } + orderedMap.select(18) should { this == Some(18) } + orderedMap.select(19) `should be` None + + println(orderedMap.select(19)) + + val orderList = ArrayList() + orderedMap.inOrder { orderList.add(it) } + + orderList shouldEqual listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18) + + val postOrderList = ArrayList() + orderedMap.postOrder { postOrderList.add(it) } + + postOrderList shouldEqual listOf(0, 1, 2, 3, 8, 7, 6, 5, 4, 10, 11, 12, 13, 18, 17, 16, 15, + 14, 9) + + val preOrderList = ArrayList() + orderedMap.preOrder { preOrderList.add(it) } + + preOrderList shouldEqual listOf(9, 4, 3, 2, 1, 0, 5, 6, 7, 8, 14, 13, 12, 11, 10, 15, 16, + 17, 18) + } +} \ No newline at end of file