├── .travis.yml ├── kotlin-algorithm-club.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ └── io │ │ └── uuddlrlrba │ │ └── ktalgs │ │ ├── math │ │ ├── Log2.kt │ │ ├── Gcd.kt │ │ ├── Binomial.kt │ │ └── NewtonMethod.kt │ │ ├── substring │ │ └── KMP.kt │ │ ├── graphs │ │ ├── NoSuchPathException.kt │ │ ├── Graph.kt │ │ ├── undirected │ │ │ ├── weighted │ │ │ │ ├── MST.kt │ │ │ │ ├── UWGraph.kt │ │ │ │ ├── KruskalMST.kt │ │ │ │ ├── BoruvkaMST.kt │ │ │ │ └── PrimMST.kt │ │ │ └── unweighted │ │ │ │ └── UUGraph.kt │ │ ├── directed │ │ │ ├── unweighted │ │ │ │ └── DUGraph.kt │ │ │ └── weighted │ │ │ │ ├── DWGraph.kt │ │ │ │ └── Dijkstra.kt │ │ ├── BFS.kt │ │ └── DFS.kt │ │ ├── sorts │ │ ├── AbstractSortStrategy.kt │ │ ├── SortUtils.kt │ │ ├── InsertionSort.kt │ │ ├── HeapSort.kt │ │ ├── SelectionSort.kt │ │ ├── BubbleSort.kt │ │ ├── ShellSort.kt │ │ ├── MergeSort.kt │ │ └── QuickSort.kt │ │ ├── search │ │ ├── AbstractSearchStrategy.kt │ │ ├── LinearSearch.kt │ │ └── BinarySearch.kt │ │ ├── geometry │ │ ├── convexhull │ │ │ ├── ConvexHullAlgorithm.kt │ │ │ ├── Quickhull.kt │ │ │ ├── GrahamScan.kt │ │ │ └── GiftWrapping.kt │ │ ├── Voronoi.kt │ │ ├── Rect.kt │ │ ├── SierpinskiTriangle.kt │ │ ├── Point.kt │ │ └── QuadTree.kt │ │ └── datastructures │ │ ├── tree │ │ ├── Tree.kt │ │ ├── BinaryTree.kt │ │ └── BinarySearchTree.kt │ │ ├── ImmutableSet.kt │ │ ├── DisjointSet.kt │ │ ├── Stack.kt │ │ ├── Queue.kt │ │ ├── Dequeue.kt │ │ ├── PriorityQueue.kt │ │ └── IndexedPriorityQueue.kt └── test │ └── io │ └── uuddlrlrba │ └── ktalgs │ ├── sorts │ ├── HeapSortTest.kt │ ├── MergeSortTest.kt │ ├── QuickSortTest.kt │ ├── ShellSortTest.kt │ ├── BubbleSortTest.kt │ ├── InsertionSortTest.kt │ ├── SelectionSortTest.kt │ └── AbstractSortTest.kt │ ├── geometry │ ├── convexhull │ │ ├── QuickhullTest.kt │ │ ├── GrahamScanTest.kt │ │ ├── GiftWrappingTest.kt │ │ └── ConvexHullTest.kt │ └── QuadTreeTest.kt │ ├── search │ ├── BinarySearchTest.kt │ ├── LinearSearchTest.kt │ └── AbstractSearchTest.kt │ ├── graphs │ └── undirected │ │ └── weighted │ │ ├── PrimMSTTest.kt │ │ ├── BoruvkaMSTTest.kt │ │ ├── KruskalMSTTest.kt │ │ └── MSTTest.kt │ ├── math │ ├── GcdKtTest.kt │ ├── NewtonMethodKtTest.kt │ └── BinomialTest.kt │ └── datastructures │ ├── PriorityQueueTest.kt │ ├── IndexedPriorityQueueTest.kt │ ├── DisjointSetTest.kt │ ├── ImmutableSetTest.kt │ ├── QueueTest.kt │ ├── StackTest.kt │ ├── DequeueTest.kt │ └── tree │ └── BinarySearchTreeTest.kt ├── .gitignore ├── git-commit-convention.md ├── LICENSE ├── gradlew.bat ├── README.md └── gradlew /.travis.yml: -------------------------------------------------------------------------------- 1 | language: groovy 2 | 3 | after_success: 4 | - bash <(curl -s https://codecov.io/bash) -------------------------------------------------------------------------------- /kotlin-algorithm-club.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bmaslakov/kotlin-algorithm-club/HEAD/kotlin-algorithm-club.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bmaslakov/kotlin-algorithm-club/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/math/Log2.kt: -------------------------------------------------------------------------------- 1 | package io.uuddlrlrba.ktalgs.math 2 | 3 | fun log2(x: Int) = Math.log(x.toDouble()) / Math.log(2.toDouble()) 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 2 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 3 | 4 | .idea/ 5 | out/ 6 | .gradle/ 7 | build/ 8 | kotlin-algorithm-club.iml 9 | -------------------------------------------------------------------------------- /git-commit-convention.md: -------------------------------------------------------------------------------- 1 | #### Format of the commit message: 2 | 3 | ``` 4 | (): 5 | 6 | ``` 7 | 8 | #### Message subject (first line) 9 | 10 | First line cannot be longer than 70 characters, second line is always blank and other lines should be wrapped at 80 characters. The type and scope should always be lowercase as shown below. 11 | Allowed `` values: 12 | * add (new algorithm was added) 13 | * fix (bug fix or implementation fix) 14 | * feat (new feature to an existing algorithm, add methods or interfaces) 15 | * docs (changes to the documentation) 16 | * chore (changes in the project structure or build scripts) 17 | * test (adding test cases, refactoring tests) 18 | * style (formatting and styling) 19 | 20 | #### `` values 21 | 22 | Are equal to the corresponding package name 23 | 24 | * datastructures 25 | * graphs 26 | * math 27 | * search 28 | * sorts 29 | 30 | or file 31 | 32 | * gradle 33 | * readme 34 | 35 | or vcs 36 | 37 | * git 38 | 39 | #### `` is required and briefly describes your changes 40 | 41 | #### `` is optional 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Boris Maslakov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/substring/KMP.kt: -------------------------------------------------------------------------------- 1 | package io.uuddlrlrba.ktalgs.substring 2 | 3 | class KMP(val pat: String) { 4 | private val R: Int = 256 // the radix 5 | private val dfa: Array // the KMP automoton 6 | 7 | init { 8 | // build DFA from pattern 9 | val m = pat.length 10 | dfa = Array(R) { IntArray(m) } 11 | dfa[pat[0].toInt()][0] = 1 12 | var x = 0 13 | var j = 1 14 | while (j < m) { 15 | for (c in 0 until R) { 16 | dfa[c][j] = dfa[c][x] // Copy mismatch cases. 17 | } 18 | dfa[pat[j].toInt()][j] = j + 1 // Set match case. 19 | x = dfa[pat[j].toInt()][x] // Update restart state. 20 | j++ 21 | } 22 | } 23 | 24 | fun search(txt: String): Int { 25 | // simulate operation of DFA on text 26 | val m = pat.length 27 | val n = txt.length 28 | var i: Int = 0 29 | var j: Int 30 | j = 0 31 | while (i < n && j < m) { 32 | j = dfa[txt[i].toInt()][j] 33 | i++ 34 | } 35 | if (j == m) return i - m // found 36 | return n // not found 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/HeapSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class HeapSortTest: AbstractSortTest(HeapSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/MergeSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class MergeSortTest: AbstractSortTest(MergeSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/QuickSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class QuickSortTest: AbstractSortTest(QuickSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/ShellSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class ShellSortTest: AbstractSortTest(ShellSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/BubbleSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class BubbleSortTest: AbstractSortTest(BubbleSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/geometry/convexhull/QuickhullTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | class QuickhullTest: ConvexHullTest(Quickhull()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/geometry/convexhull/GrahamScanTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | class GrahamScanTest: ConvexHullTest(GrahamScan()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/InsertionSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class InsertionSortTest: AbstractSortTest(InsertionSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/SelectionSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | class SelectionSortTest: AbstractSortTest(SelectionSort()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/geometry/convexhull/GiftWrappingTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | class GiftWrappingTest: ConvexHullTest(GiftWrapping()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/search/BinarySearchTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.search 24 | 25 | class BinarySearchTest: AbstractSearchTest>(BinarySearch()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/search/LinearSearchTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.search 24 | 25 | class LinearSearchTest: AbstractSearchTest>(LinearSearch()) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/PrimMSTTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | class PrimMSTTest: MSTTest({ graph -> PrimMST(graph) }) 26 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/NoSuchPathException.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs 24 | 25 | class NoSuchPathException(s: String?) : Exception(s) { 26 | constructor() : this(null) 27 | } 28 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/BoruvkaMSTTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | class BoruvkaMSTTest: MSTTest({ graph -> BoruvkaMST(graph) }) 26 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/KruskalMSTTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | class KruskalMSTTest: MSTTest({ graph -> KruskalMST(graph) }) 26 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/AbstractSortStrategy.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | abstract class AbstractSortStrategy { 26 | abstract fun> perform(arr: Array) 27 | } 28 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/search/AbstractSearchStrategy.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.search 24 | 25 | abstract class AbstractSearchStrategy { 26 | abstract fun perform(arr: Array, element: T): Int 27 | } 28 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/math/Gcd.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.math 24 | 25 | fun gcd(a: Int, b: Int): Int { 26 | if (b == 0) return a 27 | return gcd(b, a % b) 28 | } 29 | 30 | fun lcm(a: Int, b: Int): Int { 31 | return a / gcd(a, b) * b 32 | } 33 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/ConvexHullAlgorithm.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | import io.uuddlrlrba.ktalgs.geometry.Point 26 | 27 | interface ConvexHullAlgorithm { 28 | fun convexHull(points: Array): Collection 29 | } 30 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/Graph.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs 24 | 25 | interface Graph { 26 | public val V: Int 27 | public var E: Int 28 | public fun adjacentVertices(from: Int): Collection 29 | 30 | public fun vertices(): IntRange = 0 until V 31 | } 32 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/search/LinearSearch.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.search 24 | 25 | class LinearSearch: AbstractSearchStrategy() { 26 | override fun perform(arr: Array, element: T): Int { 27 | for ((i, a) in arr.withIndex()) { 28 | if (a == element) { 29 | return i 30 | } 31 | } 32 | return -1 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/math/Binomial.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.math 24 | 25 | /** 26 | * This calculates C(n,k). How many ways can k be chosen from n? 27 | */ 28 | fun binomial(n: Int, k: Int): Long { 29 | var j = n - k + 1 30 | var binomial = 1L 31 | for (i in 1 until k + 1) { 32 | binomial = binomial * j / i 33 | j++ 34 | } 35 | return binomial 36 | } 37 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/math/NewtonMethod.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.math 24 | 25 | fun sqrt(c: Int, e: Double = 1e-15): Double { 26 | return sqrt(c.toDouble(), e) 27 | } 28 | 29 | fun sqrt(c: Double, e: Double = 1e-15): Double { 30 | if (c < 0) return Double.NaN 31 | var t = c 32 | while (Math.abs(t - c / t) > e * t) 33 | t = (c / t + t) / 2.0 34 | return t 35 | } 36 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/SortUtils.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | fun Array.exch(i: Int, j: Int) { 26 | val tmp = this[i] 27 | this[i] = this[j] 28 | this[j] = tmp 29 | } 30 | 31 | @Retention(AnnotationRetention.SOURCE) 32 | annotation class ComparisonSort 33 | 34 | @Retention(AnnotationRetention.SOURCE) 35 | annotation class StableSort 36 | 37 | @Retention(AnnotationRetention.SOURCE) 38 | annotation class UnstableSort 39 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/tree/Tree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures.tree 24 | 25 | class Tree(var value: Int) { 26 | val children: MutableList = mutableListOf() 27 | 28 | fun size(): Int { 29 | return children.fold(1, { size, child -> size + child.size() }) 30 | } 31 | 32 | fun height(): Int { 33 | return 1 + (children.map { it.size() }.max() ?: 0) 34 | } 35 | 36 | fun add(value: Int) { 37 | children.add(Tree(value)) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/Voronoi.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry 24 | 25 | /** 26 | * Naïve implementation, takes O(N) for each request. 27 | */ 28 | class Voronoi(private val points: Collection, private val distanceFunc: (Point, Point) -> (Double)) { 29 | 30 | val count: Int 31 | get() = points.size 32 | 33 | fun region(p: Point): Point { 34 | return points.minBy { distanceFunc(p, it) }!! 35 | } 36 | 37 | init { 38 | if (points.isEmpty()) throw IllegalArgumentException("points must be non empty") 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/search/BinarySearch.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.search 24 | 25 | class BinarySearch>: AbstractSearchStrategy() { 26 | override fun perform(arr: Array, element: T): Int { 27 | var lo = 0 28 | var hi = arr.size - 1 29 | while (lo <= hi) { 30 | val mid = (lo + hi) / 2 31 | when { 32 | element < arr[mid] -> hi = mid - 1 33 | element > arr[mid] -> lo = mid + 1 34 | else -> return mid 35 | } 36 | } 37 | return -1 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/MST.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | interface MST { 26 | /** 27 | * Returns the edges in a minimum spanning tree (or forest). 28 | * @return the edges in a minimum spanning tree (or forest) as 29 | * * an iterable of edges 30 | */ 31 | fun edges(): Iterable 32 | 33 | /** 34 | * Returns the sum of the edge weights in a minimum spanning tree (or forest). 35 | * @return the sum of the edge weights in a minimum spanning tree (or forest) 36 | */ 37 | fun weight(): Double 38 | } 39 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/undirected/unweighted/UUGraph.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.unweighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | import io.uuddlrlrba.ktalgs.graphs.Graph 27 | 28 | class UUGraph(public override val V: Int): Graph { 29 | public override var E: Int = 0 30 | private val adj: Array> = Array(V) { Queue() } 31 | 32 | public fun addEdge(v: Int, w: Int) { 33 | adj[v].add(w) 34 | adj[w].add(v) 35 | E++ 36 | } 37 | 38 | public override fun adjacentVertices(v: Int): Collection { 39 | return adj[v] 40 | } 41 | 42 | public fun degree(v: Int): Int { 43 | return adj[v].size 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/InsertionSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | /** 26 | * Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. 27 | * Each iteration, insertion sort removes one element from the input data, finds the location it belongs within 28 | * the sorted list, and inserts it there. It repeats until no input elements remain. 29 | */ 30 | @ComparisonSort 31 | @StableSort 32 | class InsertionSort: AbstractSortStrategy() { 33 | override fun > perform(arr: Array) { 34 | for (i in 1 until arr.size) { 35 | for (j in i downTo 1) { 36 | if (arr[j - 1] < arr[j]) break 37 | arr.exch(j, j - 1) 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/directed/unweighted/DUGraph.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.directed.unweighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | import io.uuddlrlrba.ktalgs.graphs.Graph 27 | 28 | class DUGraph(public override val V: Int): Graph { 29 | override var E: Int = 0 30 | private val adj: Array> = Array(V) { Queue() } 31 | private val indegree: IntArray = IntArray(V) 32 | 33 | public fun addEdge(from: Int, to: Int) { 34 | adj[from].add(to) 35 | indegree[to]++ 36 | E++ 37 | } 38 | 39 | public override fun adjacentVertices(from: Int): Collection { 40 | return adj[from] 41 | } 42 | 43 | public fun outdegree(from: Int): Int { 44 | return adj[from].size 45 | } 46 | 47 | public fun indegree(v: Int): Int { 48 | return indegree[v] 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/math/GcdKtTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.math 24 | 25 | import org.junit.Test 26 | 27 | import org.junit.Assert.* 28 | 29 | class GcdKtTest { 30 | @Test 31 | fun gcd() { 32 | assertEquals(1, gcd(1, 1)) 33 | assertEquals(8, gcd(24, 16)) 34 | assertEquals(8, gcd(16, 24)) 35 | assertEquals(16, gcd(16, 16)) 36 | assertEquals(1, gcd(13, 29)) 37 | assertEquals(8, gcd(40, 16)) 38 | assertEquals(5, gcd(40, 15)) 39 | } 40 | 41 | @Test 42 | fun lcm() { 43 | assertEquals(1, lcm(1, 1)) 44 | assertEquals(48, lcm(24, 16)) 45 | assertEquals(48, lcm(16, 24)) 46 | assertEquals(16, lcm(16, 16)) 47 | assertEquals(377, lcm(13, 29)) 48 | assertEquals(80, lcm(40, 16)) 49 | assertEquals(120, lcm(40, 15)) 50 | assertEquals(1000000, lcm(1000000, 1000000)) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/PriorityQueueTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | import java.util.NoSuchElementException 28 | 29 | class PriorityQueueTest { 30 | @Test 31 | fun emptyTest() { 32 | val pq = PriorityQueue(3) 33 | Assert.assertEquals(0, pq.size) 34 | Assert.assertTrue(pq.isEmpty()) 35 | } 36 | 37 | @Test(expected= NoSuchElementException::class) 38 | fun exceptionTest() { 39 | val pq = PriorityQueue(3) 40 | pq.peek() 41 | } 42 | 43 | @Test 44 | fun naiveTest() { 45 | val pq = PriorityQueue(3) 46 | for (i in 10 downTo 1) { 47 | pq.add(i) 48 | Assert.assertEquals(i, pq.peek()) 49 | } 50 | for (i in 1..10) { 51 | Assert.assertEquals(i, pq.poll()) 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/HeapSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.PriorityQueue 26 | 27 | /** 28 | * Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection 29 | * sort where we first find the maximum element and place the maximum element at the end. We repeat the same process 30 | * for remaining element. 31 | */ 32 | @ComparisonSort 33 | @UnstableSort 34 | class HeapSort : AbstractSortStrategy() { 35 | override fun > perform(arr: Array) { 36 | for (k in arr.size / 2 downTo 1) { 37 | PriorityQueue.sink(arr as Array, k - 1, arr.size - 1, reverseOrder()) 38 | } 39 | for (k in arr.size downTo 1) { 40 | arr.exch(0, k - 1) 41 | PriorityQueue.sink(arr as Array, 0, k - 2, reverseOrder()) 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/IndexedPriorityQueueTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | import java.util.NoSuchElementException 28 | 29 | class IndexedPriorityQueueTest { 30 | @Test 31 | fun emptyTest() { 32 | val pq = IndexedPriorityQueue(3) 33 | Assert.assertEquals(0, pq.size) 34 | Assert.assertTrue(pq.isEmpty()) 35 | } 36 | 37 | @Test(expected= NoSuchElementException::class) 38 | fun exceptionTest() { 39 | val pq = IndexedPriorityQueue(3) 40 | pq.peek() 41 | } 42 | 43 | @Test 44 | fun naiveTest() { 45 | val pq = IndexedPriorityQueue(20) 46 | for (i in 10 downTo 1) { 47 | pq.insert(20 - i, i) 48 | Assert.assertEquals(Pair(20 - i, i), pq.peek()) 49 | } 50 | for (i in 1..10) { 51 | Assert.assertEquals(Pair(20 - i, i), pq.poll()) 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/geometry/QuadTreeTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | class QuadTreeTest { 29 | @Test 30 | fun naiveTest1() { 31 | val qt = quadTreeOf(Rect(0, 0, 100, 100), 32 | Point(5, 20) to "Foo", 33 | Point(50, 32) to "Bar", 34 | Point(47, 96) to "Baz", 35 | Point(50, 50) to "Bing", 36 | Point(12, 0) to "Bong" 37 | ) 38 | 39 | val points1 = qt[Rect(4, 0, 51, 98)].sorted() 40 | Assert.assertEquals(listOf("Bar", "Baz", "Bing", "Bong", "Foo"), points1) 41 | 42 | val points2 = qt[Rect(5, 0, 50, 96)].sorted() 43 | Assert.assertEquals(listOf("Bar", "Baz", "Bing", "Bong", "Foo"), points2) 44 | 45 | val points3 = qt[Rect(55, 0, 50, 96)] 46 | Assert.assertEquals(0, points3.count()) 47 | 48 | val points4 = qt[Rect(4, 19, 6, 21)].sorted() 49 | Assert.assertEquals(listOf("Foo"), points4) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/math/NewtonMethodKtTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.math 24 | 25 | import org.junit.Test 26 | 27 | import org.junit.Assert.* 28 | 29 | class NewtonMethodKtTest { 30 | @Test 31 | fun sqrt() { 32 | assertTrue(sqrt(-2.0).isNaN()) 33 | assertTrue(sqrt(-2.0, 0.toDouble()).isNaN()) 34 | assertEquals(2.toDouble(), sqrt(4.toDouble()), 1e-15) 35 | assertEquals(4.toDouble(), sqrt(16.toDouble()), 1e-12) 36 | for (i in 7 until 99) { 37 | for (j in -15 until -1) { 38 | assertEquals(sqrt(i.toDouble()), sqrt(i.toDouble()), j.toDouble()) 39 | } 40 | } 41 | } 42 | 43 | @Test 44 | fun sqrt1() { 45 | assertTrue(sqrt(-2).isNaN()) 46 | assertEquals(2.toDouble(), sqrt(4), 1e-15) 47 | assertEquals(4.toDouble(), sqrt(16), 1e-12) 48 | for (i in 7 until 99) { 49 | for (j in -15 until -1) { 50 | assertEquals(sqrt(i), sqrt(i), j.toDouble()) 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/BFS.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | 27 | class BFS { 28 | companion object Implementations { 29 | fun iterative(graph: Graph, levelOrder: ((Int) -> Unit)? = null) { 30 | val visited = BooleanArray(graph.V) 31 | val queue = Queue() 32 | for (i in 0 until graph.V) { 33 | if (!visited[i]) { 34 | queue.add(i) 35 | visited[i] = true 36 | levelOrder?.invoke(i) 37 | while (!queue.isEmpty()) { 38 | val v = queue.poll() 39 | for (w in graph.adjacentVertices(v)) { 40 | if (!visited[w]) { 41 | queue.add(w) 42 | visited[w] = true 43 | levelOrder?.invoke(i) 44 | } 45 | } 46 | } 47 | } 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/Rect.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry 24 | 25 | data class Rect(val x1: Int, val y1: Int, val x2: Int, val y2: Int) { 26 | val width = x2 - x1 27 | val height = y2 - y1 28 | val origin = Point(x1, y1) 29 | val center = Point(origin.x + width / 2, origin.y + height / 2) 30 | val TL = origin 31 | val BR = Point(origin.x + width, origin.y + height) 32 | 33 | constructor(TL: Point, BR: Point) : this(TL, (BR.x - TL.x), (BR.y - TL.y)) 34 | 35 | constructor(origin: Point, width: Int, height: Int) : this(origin.x, origin.y, origin.x + width, origin.y + height) 36 | 37 | fun isInside(point: Point): Boolean = 38 | point.x >= origin.x && point.y >= origin.y && 39 | point.x <= origin.x + width && point.y <= origin.y + height 40 | 41 | fun cover(point: Point): Rect = 42 | Rect(Point(minOf(x1, point.x), minOf(y1, point.y)), Point(maxOf(x2, point.x), maxOf(y2, point.y))) 43 | 44 | fun intersects(other: Rect) = 45 | !(other.x1 > this.x2 || other.x2 < this.x1 || other.y1 > this.y2 || other.y2 < this.y1) 46 | } 47 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/ImmutableSet.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import io.uuddlrlrba.ktalgs.search.BinarySearch 26 | 27 | /** 28 | * The class represents set of comparables. The values are stored in a sorted array, 29 | * and the inclusion queries perform binary search, taking logarithmic time in the worst case. 30 | */ 31 | class ImmutableSet>(values: Array): Set { 32 | private val arr: Array = values.sortedArray() 33 | private val bs = BinarySearch() // TODO: remove 34 | 35 | override val size: Int 36 | get() = arr.size 37 | 38 | override fun contains(element: T): Boolean { 39 | return bs.perform(arr, element) != -1 40 | } 41 | 42 | override fun containsAll(elements: Collection): Boolean { 43 | return elements.all { contains(it) } 44 | } 45 | 46 | override fun isEmpty(): Boolean { 47 | return size == 0 48 | } 49 | 50 | override fun iterator(): Iterator { 51 | return arr.iterator() 52 | } 53 | } 54 | 55 | fun > immutableSetOf(vararg elements: T): ImmutableSet { 56 | return ImmutableSet(elements.copyOf()) 57 | } 58 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/math/BinomialTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.math 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | class BinomialTest { 29 | @Test 30 | fun test1() { 31 | Assert.assertEquals(0, binomial(0, 1)) 32 | Assert.assertEquals(1, binomial(1, 1)) 33 | Assert.assertEquals(2, binomial(2, 1)) 34 | Assert.assertEquals(3, binomial(3, 1)) 35 | Assert.assertEquals(3, binomial(3, 2)) 36 | Assert.assertEquals(4, binomial(4, 1)) 37 | 38 | Assert.assertEquals(1, binomial(5, 0)) 39 | Assert.assertEquals(5, binomial(5, 1)) 40 | Assert.assertEquals(10, binomial(5, 2)) 41 | Assert.assertEquals(10, binomial(5, 3)) 42 | Assert.assertEquals(5, binomial(5, 4)) 43 | Assert.assertEquals(1, binomial(5, 5)) 44 | 45 | Assert.assertEquals(1, binomial(6, 0)) 46 | Assert.assertEquals(6, binomial(6, 1)) 47 | Assert.assertEquals(15, binomial(6, 2)) 48 | Assert.assertEquals(20, binomial(6, 3)) 49 | Assert.assertEquals(15, binomial(6, 4)) 50 | Assert.assertEquals(6, binomial(6, 5)) 51 | Assert.assertEquals(1, binomial(6, 6)) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/DisjointSet.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | class DisjointSet(val size: Int) { 26 | private val parent = IntArray(size) 27 | private val rank = ByteArray(size) 28 | public var count = size 29 | private set 30 | 31 | init { 32 | for (i in parent.indices) { 33 | parent[i] = i 34 | } 35 | } 36 | 37 | public fun connected(v: Int, w: Int): Boolean { 38 | return find(v) == find(w) 39 | } 40 | 41 | public fun find(v: Int): Int { 42 | var v = v 43 | while (parent[v] != v) { 44 | parent[v] = parent[parent[v]] 45 | v = parent[v] 46 | } 47 | return v 48 | } 49 | 50 | public fun union(v: Int, w: Int) { 51 | val rootV = find(v) 52 | val rootW = find(w) 53 | if (rootV == rootW) return 54 | if (rank[rootV] > rank[rootW]) { 55 | parent[rootW] = rootV 56 | } else if (rank[rootW] > rank[rootV]) { 57 | parent[rootV] = rootW 58 | } else { 59 | parent[rootV] = rootW 60 | rank[rootW]++ 61 | } 62 | count-- 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/Quickhull.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | import io.uuddlrlrba.ktalgs.geometry.Point 26 | 27 | class Quickhull: ConvexHullAlgorithm { 28 | override fun convexHull(points: Array): Collection { 29 | if (points.size < 3) throw IllegalArgumentException("there must be at least 3 points") 30 | val left = points.min()!! 31 | val right = points.max()!! 32 | return quickHull(points.asList(), left, right) + quickHull(points.asList(), right, left) 33 | } 34 | 35 | private fun quickHull(points: Collection, first: Point, second: Point): Collection { 36 | val pointsLeftOfLine = points 37 | .filter { it.isLeftOfLine(first, second) } 38 | .map { Pair(it, it.distanceToLine(first, second)) } 39 | if (pointsLeftOfLine.isEmpty()) { 40 | return listOf(second) 41 | } else { 42 | val max = pointsLeftOfLine.maxBy { it.second }!!.first 43 | val newPoints = pointsLeftOfLine.map { it.first } 44 | return quickHull(newPoints, first, max) + quickHull(newPoints, max, second) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/SelectionSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | /** 26 | * Selection sort is a simple sorting algorithm dividing the input list into two parts: the sublist of items already 27 | * sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining 28 | * to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist 29 | * is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) 30 | * element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element 31 | * (putting it in sorted order), and moving the sublist boundaries one element to the right. 32 | */ 33 | @ComparisonSort 34 | @UnstableSort 35 | class SelectionSort : AbstractSortStrategy() { 36 | public override fun> perform(arr: Array) { 37 | for (i in arr.indices) { 38 | var min = i 39 | for (j in i + 1 until arr.size) { 40 | if (arr[j] < arr[min]) { 41 | min = j 42 | } 43 | } 44 | if (min != i) arr.exch(min, i) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/DisjointSetTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | class DisjointSetTest { 29 | @Test 30 | fun sizeTest() { 31 | val set = DisjointSet(10) 32 | Assert.assertEquals(10, set.count) 33 | Assert.assertEquals(10, set.size) 34 | set.union(0, 1) 35 | Assert.assertEquals(9, set.count) 36 | Assert.assertEquals(10, set.size) 37 | set.union(0, 2) 38 | Assert.assertEquals(8, set.count) 39 | Assert.assertEquals(10, set.size) 40 | } 41 | 42 | @Test 43 | fun naiveTest() { 44 | val set = DisjointSet(10) 45 | for (i in 1..set.size-1) { 46 | Assert.assertFalse(set.connected(i, i - 1)) 47 | } 48 | set.union(1, 2) 49 | Assert.assertTrue(set.connected(1, 2)) 50 | set.union(1, 3) 51 | Assert.assertTrue(set.connected(1, 3)) 52 | Assert.assertTrue(set.connected(2, 3)) 53 | set.union(3, 4) 54 | Assert.assertTrue(set.connected(2, 4)) 55 | Assert.assertFalse(set.connected(0, 1)) 56 | Assert.assertFalse(set.connected(0, 5)) 57 | Assert.assertFalse(set.connected(4, 5)) 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/BubbleSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | /** 26 | * Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares 27 | * each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated 28 | * until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, 29 | * is named for the way smaller or larger elements "bubble" to the top of the list. Although the algorithm is simple, 30 | * it is too slow and impractical for most problems even when compared to insertion sort. It can be practical 31 | * if the input is usually in sorted order but may occasionally have some out-of-order elements nearly in position. 32 | */ 33 | @ComparisonSort 34 | @StableSort 35 | class BubbleSort : AbstractSortStrategy() { 36 | public override fun> perform(arr: Array) { 37 | var exchanged: Boolean 38 | do { 39 | exchanged = false 40 | for (i in 1 until arr.size) { 41 | if (arr[i] < arr[i - 1]) { 42 | arr.exch(i, i - 1) 43 | exchanged = true 44 | } 45 | } 46 | } while (exchanged) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/directed/weighted/DWGraph.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.directed.weighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | import io.uuddlrlrba.ktalgs.datastructures.Stack 27 | import io.uuddlrlrba.ktalgs.graphs.Graph 28 | 29 | class DWGraph(public override val V: Int): Graph { 30 | public override var E: Int = 0 31 | private val adj: Array> = Array(V) { Queue() } 32 | private val indegree: IntArray = IntArray(V) 33 | 34 | public class Edge(public val from: Int, public val to: Int, public val weight: Double) 35 | 36 | public fun addEdge(from: Int, to: Int, weight: Double) { 37 | val edge = Edge(from, to, weight) 38 | adj[from].add(edge) 39 | indegree[to]++ 40 | E++ 41 | } 42 | 43 | public fun edges(): Collection { 44 | val stack = Stack() 45 | adj.flatMap { it }.forEach { stack.push(it) } 46 | return stack 47 | } 48 | 49 | public fun adjacentEdges(from: Int): Collection { 50 | return adj[from] 51 | } 52 | 53 | public override fun adjacentVertices(from: Int): Collection { 54 | return adjacentEdges(from).map { it.to } 55 | } 56 | 57 | public fun outdegree(v: Int): Int { 58 | return adj[v].size 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/SierpinskiTriangle.kt: -------------------------------------------------------------------------------- 1 | package io.uuddlrlrba.ktalgs.geometry 2 | 3 | import io.uuddlrlrba.ktalgs.math.log2 4 | 5 | class SierpinskiTriangle { 6 | /** 7 | * @param d base of the triangle (i.e. the smallest dimension) 8 | * @param n fractalization depth (must be less than log2(d)) 9 | * @throws IllegalArgumentException if n > log2(d) 10 | */ 11 | fun makeTriangles(base: Int, n: Int): Array { 12 | if (n > log2(base)) throw IllegalArgumentException("fractalization depth must be less than log2(base): " + 13 | "$n > ${log2(base).toInt()}") 14 | val arr = Array(base, { BooleanArray(base * 2 - 1) }) 15 | drawTriangles(n, arr, 0, 0, base - 1, base * 2 - 2) 16 | return arr 17 | } 18 | 19 | fun drawTriangles(n: Int, arr: Array, top: Int, left: Int, bottom: Int, right: Int) { 20 | if (n > 0) { 21 | val width = right - left 22 | val height = bottom - top 23 | drawTriangles(n - 1, arr, 24 | top, 25 | left + width / 4 + 1, 26 | top + height / 2, 27 | right - width / 4 - 1 28 | ) 29 | drawTriangles(n - 1, arr, 30 | top + 1 + height / 2, 31 | left, 32 | bottom, 33 | left + width / 2 - 1 34 | ) 35 | drawTriangles(n - 1, arr, 36 | top + 1 + height / 2, 37 | left + width / 2 + 1, 38 | bottom, 39 | right 40 | ) 41 | } else { 42 | drawTriangles(arr, top, left, bottom, right) 43 | } 44 | } 45 | 46 | fun drawTriangles(arr: Array, top: Int, left: Int, bottom: Int, right: Int) { 47 | val height = bottom - top 48 | val width = right - left 49 | for (i in 0..height) { 50 | for (j in (height - i)..width / 2) { 51 | arr[top + i][left + j] = true 52 | } 53 | for (j in (width / 2..width / 2 + i)) { 54 | arr[top + i][left + j] = true 55 | } 56 | } 57 | } 58 | } 59 | 60 | fun main(args : Array) { 61 | SierpinskiTriangle() 62 | .makeTriangles(128, 7) 63 | .map { array -> 64 | array.map { if (it) 'x' else ' ' }.joinToString(separator = "") 65 | } 66 | .forEach { println(it) } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/ShellSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | /** 26 | * Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a 27 | * generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by 28 | * sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be 29 | * compared. Starting with far apart elements, it can move some out-of-place elements into position faster than 30 | * a simple nearest neighbor exchange. Donald Shell published the first version of this sort in 1959. 31 | * This implementation uses the gap sequence proposed by Pratt in 1971: 1, 4, 13, 40... 32 | */ 33 | @ComparisonSort 34 | @StableSort 35 | class ShellSort : AbstractSortStrategy() { 36 | public override fun> perform(arr: Array) { 37 | var h = 1 38 | while (h < arr.size / 3) { 39 | h = h * 3 + 1 40 | } 41 | 42 | while (h >= 1) { 43 | for (i in h until arr.size) { 44 | for (j in i downTo h step h) { 45 | if (arr[j - h] < arr[j]) break 46 | arr.exch(j, j - h) 47 | } 48 | } 49 | h /= 3 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/ImmutableSetTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | class ImmutableSetTest { 29 | @Test 30 | fun test1() { 31 | Assert.assertFalse(immutableSetOf(3).contains(1)) 32 | Assert.assertFalse(immutableSetOf(3).contains(2)) 33 | Assert.assertFalse(immutableSetOf(3).contains(4)) 34 | Assert.assertFalse(immutableSetOf(3).contains(5)) 35 | Assert.assertTrue(immutableSetOf(3).contains(3)) 36 | } 37 | 38 | @Test 39 | fun test2() { 40 | val set = immutableSetOf(*(10 downTo 1).toList().toTypedArray()) 41 | for (v in set) { 42 | Assert.assertTrue(set.contains(v)) 43 | } 44 | Assert.assertEquals(10, set.size) 45 | Assert.assertFalse(set.isEmpty()) 46 | Assert.assertFalse(set.contains(42)) 47 | Assert.assertFalse(set.contains(-42)) 48 | } 49 | 50 | @Test 51 | fun test3() { 52 | val set = immutableSetOf(*(0..100).toList().toTypedArray()) 53 | for (v in -100..-1) { 54 | Assert.assertFalse(set.contains(v)) 55 | } 56 | for (v in 0..100) { 57 | Assert.assertTrue(set.contains(v)) 58 | } 59 | for (v in 101..200) { 60 | Assert.assertFalse(set.contains(v)) 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/tree/BinaryTree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures.tree 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | 27 | class BinaryTree(var value: Int, var left: BinaryTree?, var right: BinaryTree?) { 28 | constructor(value: Int): this(value, null, null) 29 | 30 | fun size(): Int { 31 | var size = 1 32 | if (left != null) { 33 | size += left!!.size() 34 | } 35 | if (right != null) { 36 | size += right!!.size() 37 | } 38 | return size 39 | } 40 | 41 | fun height(): Int { 42 | val left = if (left == null) 0 else left!!.height() 43 | val right = if (right == null) 0 else right!!.height() 44 | return maxOf(left, right) + 1 45 | } 46 | 47 | fun add(value: Int) { 48 | // adds the on the first empty level 49 | val queue = Queue() 50 | queue.add(this) 51 | while (!queue.isEmpty()) { 52 | val x = queue.poll() 53 | if (x.left == null) { 54 | x.left = BinaryTree(value) 55 | return 56 | } else if (x.right == null) { 57 | x.right = BinaryTree(value) 58 | return 59 | } else { 60 | queue.add(x.left!!) 61 | queue.add(x.right!!) 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/UWGraph.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | import io.uuddlrlrba.ktalgs.graphs.Graph 27 | 28 | class UWGraph(public override val V: Int): Graph { 29 | public override var E: Int = 0 30 | private val adj: Array> = Array(V) { Queue() } 31 | 32 | public class Edge(public val v: Int, public val w: Int, public val weight: Double): Comparable { 33 | override fun compareTo(other: Edge): Int { 34 | return this.weight.compareTo(other.weight) 35 | } 36 | 37 | fun other(s: Int): Int { 38 | if (s == v) return w 39 | if (s == w) return v 40 | throw IllegalArgumentException() 41 | } 42 | } 43 | 44 | public fun addEdge(v: Int, w: Int, weight: Double) { 45 | val edge = Edge(v, w, weight) 46 | adj[v].add(edge) 47 | adj[w].add(edge) 48 | E++ 49 | } 50 | 51 | public fun adjacentEdges(v: Int): Collection { 52 | return adj[v] 53 | } 54 | 55 | public override fun adjacentVertices(v: Int): Collection { 56 | return adjacentEdges(v).map { it.other(v) } 57 | } 58 | 59 | public fun degree(v: Int): Int { 60 | return adj[v].size 61 | } 62 | 63 | public fun edges(): Collection { 64 | return adj.flatMap { it } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/KruskalMST.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.DisjointSet 26 | import io.uuddlrlrba.ktalgs.datastructures.PriorityQueue 27 | import io.uuddlrlrba.ktalgs.datastructures.Queue 28 | 29 | /** 30 | * Kruskal's algorithm will grow a solution from the cheapest edge by adding the next cheapest edge, 31 | * provided that it doesn't create a cycle. 32 | */ 33 | class KruskalMST(G: UWGraph): MST { 34 | var weight: Double = 0.0 35 | var edges: Queue = Queue() 36 | 37 | /** 38 | * Compute a minimum spanning tree (or forest) of an edge-weighted graph. 39 | * @param G the edge-weighted graph 40 | */ 41 | init { 42 | val pq = PriorityQueue(G.V, compareBy({ it.weight })) 43 | for (v in G.vertices()) { 44 | for (e in G.adjacentEdges(v)) { 45 | pq.add(e) 46 | } 47 | } 48 | 49 | val set = DisjointSet(G.V) 50 | while (!pq.isEmpty()) { 51 | val edge = pq.poll() 52 | if (!set.connected(edge.v, edge.w)) { 53 | edges.add(edge) 54 | set.union(edge.v, edge.w) 55 | weight += edge.weight 56 | } 57 | } 58 | } 59 | 60 | override fun edges(): Iterable { 61 | return edges 62 | } 63 | 64 | override fun weight(): Double { 65 | return weight 66 | } 67 | } -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/MergeSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | /** 26 | * Invented in 1945 by John von Neumann, merge sort is an efficient algorithm using the divide and conquer approach 27 | * which is to divide a big problem into smaller problems and solve them. Conceptually, a merge sort works as follows: 28 | * 1) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). 29 | * 2) Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. 30 | */ 31 | @ComparisonSort 32 | @StableSort 33 | class MergeSort: AbstractSortStrategy() { 34 | override fun > perform(arr: Array) { 35 | val aux = arr.clone() 36 | sort(arr, aux, 0, arr.size - 1) 37 | } 38 | 39 | private fun > sort(arr: Array, aux: Array, lo: Int, hi: Int) { 40 | if (hi <= lo) return 41 | val mid = (lo + hi) / 2 42 | sort(arr, aux, lo, mid) 43 | sort(arr, aux, mid + 1, hi) 44 | merge(arr, aux, lo, mid, hi) 45 | } 46 | 47 | private fun > merge(arr: Array, aux: Array, lo: Int, mid: Int, hi: Int) { 48 | System.arraycopy(arr, lo, aux, lo, hi - lo + 1) 49 | 50 | var i = lo 51 | var j = mid + 1 52 | for (k in lo..hi) { 53 | when { 54 | i > mid -> arr[k] = aux[j++] 55 | j > hi -> arr[k] = aux[i++] 56 | aux[j] < aux[i] -> arr[k] = aux[j++] 57 | else -> arr[k] = aux[i++] 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/QueueTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | import java.util.* 28 | 29 | class QueueTest { 30 | @Test 31 | fun emptyTest() { 32 | val queue = Queue() 33 | Assert.assertEquals(0, queue.size) 34 | Assert.assertTrue(queue.isEmpty()) 35 | } 36 | 37 | @Test(expected= NoSuchElementException::class) 38 | fun exceptionTest() { 39 | val queue = Queue() 40 | queue.peek() 41 | } 42 | 43 | @Test 44 | fun naiveTest() { 45 | val queue = Queue() 46 | for (i in 0..10) { 47 | queue.add(i) 48 | } 49 | for (i in 0..10) { 50 | Assert.assertEquals(i, queue.peek()) 51 | Assert.assertEquals(i, queue.poll()) 52 | } 53 | Assert.assertEquals(0, queue.size) 54 | } 55 | 56 | @Test 57 | fun naiveIteratorTest() { 58 | val queue = Queue() 59 | for (i in 0..10) { 60 | queue.add(i) 61 | } 62 | 63 | var k = 0 64 | for (i in queue) { 65 | Assert.assertEquals(i, k++) 66 | } 67 | } 68 | 69 | @Test 70 | fun naiveContainsTest() { 71 | val queue = Queue() 72 | for (i in 0..10) { 73 | queue.add(i) 74 | } 75 | 76 | for (i in 0..10) { 77 | Assert.assertTrue(queue.contains(i)) 78 | } 79 | 80 | Assert.assertFalse(queue.contains(100)) 81 | Assert.assertFalse(queue.contains(101)) 82 | Assert.assertFalse(queue.contains(103)) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/StackTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | import java.util.* 28 | 29 | class StackTest { 30 | @Test 31 | fun emptyTest() { 32 | val stack = Stack() 33 | Assert.assertEquals(0, stack.size) 34 | Assert.assertTrue(stack.isEmpty()) 35 | } 36 | 37 | @Test(expected=NoSuchElementException::class) 38 | fun exceptionTest() { 39 | val stack = Stack() 40 | stack.peek() 41 | } 42 | 43 | @Test 44 | fun naiveTest() { 45 | val stack = Stack() 46 | for (i in 0..10) { 47 | stack.push(i) 48 | } 49 | for (i in 10 downTo 0) { 50 | Assert.assertEquals(i, stack.peek()) 51 | Assert.assertEquals(i, stack.poll()) 52 | } 53 | Assert.assertEquals(0, stack.size) 54 | } 55 | 56 | @Test 57 | fun naiveIteratorTest() { 58 | val stack = Stack() 59 | for (i in 0..10) { 60 | stack.push(i) 61 | } 62 | 63 | var k = 10 64 | for (i in stack) { 65 | Assert.assertEquals(i, k--) 66 | } 67 | } 68 | 69 | @Test 70 | fun naiveContainsTest() { 71 | val stack = Stack() 72 | for (i in 0..10) { 73 | stack.push(i) 74 | } 75 | 76 | for (i in 0..10) { 77 | Assert.assertTrue(stack.contains(i)) 78 | } 79 | 80 | Assert.assertFalse(stack.contains(100)) 81 | Assert.assertFalse(stack.contains(101)) 82 | Assert.assertFalse(stack.contains(103)) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/sorts/AbstractSortTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | abstract class AbstractSortTest(val strategy: T) { 29 | @Test 30 | fun emptyTest() { 31 | val arr = arrayOf() 32 | strategy.perform(arr) 33 | Assert.assertArrayEquals(arrayOf(), arr) 34 | } 35 | 36 | @Test 37 | fun singletonTest() { 38 | val arr = arrayOf(1) 39 | strategy.perform(arr) 40 | Assert.assertArrayEquals(arrayOf(1), arr) 41 | } 42 | 43 | @Test 44 | fun twoElementsInOrderTest() { 45 | val arr = arrayOf(42, 43) 46 | strategy.perform(arr) 47 | Assert.assertArrayEquals(arrayOf(42, 43), arr) 48 | } 49 | 50 | @Test 51 | fun twoElementsOutOfOrderTest() { 52 | val arr = arrayOf(43, 42) 53 | strategy.perform(arr) 54 | Assert.assertArrayEquals(arrayOf(42, 43), arr) 55 | } 56 | 57 | @Test 58 | fun twoElementsEqualTest() { 59 | val arr = arrayOf(42, 42) 60 | strategy.perform(arr) 61 | Assert.assertArrayEquals(arrayOf(42, 42), arr) 62 | } 63 | 64 | @Test 65 | fun tenElementsReverseTest() { 66 | val arr = arrayOf(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) 67 | strategy.perform(arr) 68 | Assert.assertArrayEquals(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), arr) 69 | } 70 | 71 | @Test 72 | fun tenElementsTest() { 73 | val arr = arrayOf(3, 2, 7, 6, 1, 8, 10, 9, 4, 5) 74 | strategy.perform(arr) 75 | Assert.assertArrayEquals(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), arr) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/DequeueTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | import java.util.* 28 | 29 | class DequeueTest { 30 | @Test 31 | fun emptyTest() { 32 | val dequeue = Dequeue() 33 | Assert.assertEquals(0, dequeue.size) 34 | Assert.assertTrue(dequeue.isEmpty()) 35 | } 36 | 37 | @Test(expected= NoSuchElementException::class) 38 | fun exceptionTest() { 39 | val dequeue = Dequeue() 40 | dequeue.peekFirst() 41 | } 42 | 43 | @Test 44 | fun naiveTest() { 45 | val dequeue = Dequeue() 46 | for (i in 0..10) { 47 | dequeue.add(i) 48 | } 49 | for (i in 0..5) { 50 | Assert.assertEquals(i, dequeue.peekFirst()) 51 | Assert.assertEquals(i, dequeue.pollFirst()) 52 | } 53 | for (i in 10..6) { 54 | Assert.assertEquals(i, dequeue.peekLast()) 55 | Assert.assertEquals(i, dequeue.pollLast()) 56 | } 57 | } 58 | 59 | @Test 60 | fun naiveIteratorTest() { 61 | val dequeue = Dequeue() 62 | for (i in 0..10) { 63 | dequeue.add(i) 64 | } 65 | 66 | var k = 0 67 | for (i in dequeue) { 68 | Assert.assertEquals(i, k++) 69 | } 70 | } 71 | 72 | @Test 73 | fun naiveContainsTest() { 74 | val dequeue = Dequeue() 75 | for (i in 0..10) { 76 | dequeue.add(i) 77 | } 78 | 79 | for (i in 0..10) { 80 | Assert.assertTrue(dequeue.contains(i)) 81 | } 82 | 83 | Assert.assertFalse(dequeue.contains(100)) 84 | Assert.assertFalse(dequeue.contains(101)) 85 | Assert.assertFalse(dequeue.contains(103)) 86 | } 87 | } -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/Point.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry 24 | 25 | data class Point(val x: Int, val y: Int): Comparable { 26 | override fun compareTo(other: Point): Int { 27 | if (x == other.x) return y.compareTo(other.y) 28 | return x.compareTo(other.x) 29 | } 30 | 31 | fun isLeftOfLine(from: Point, to: Point): Boolean { 32 | return crossProduct(from, to) > 0 33 | } 34 | 35 | fun crossProduct(origin: Point, p2: Point): Int { 36 | return (p2.x - origin.x) * (this.y - origin.y) - (p2.y - origin.y) * (this.x - origin.x) 37 | } 38 | 39 | fun distanceToLine(a: Point, b: Point): Double { 40 | return Math.abs((b.x - a.x) * (a.y - this.y) - (a.x - this.x) * (b.y - a.y)) / 41 | Math.sqrt(Math.pow((b.x - a.x).toDouble(), 2.0) + Math.pow((b.y - a.y).toDouble(), 2.0)) 42 | } 43 | 44 | fun euclideanDistanceTo(that: Point): Double { 45 | return EUCLIDEAN_DISTANCE_FUNC(this, that) 46 | } 47 | 48 | fun manhattanDistanceTo(that: Point): Double { 49 | return MANHATTAN_DISTANCE_FUNC(this, that) 50 | } 51 | 52 | companion object { 53 | // < 0 : Counterclockwise 54 | // = 0 : p, q and r are colinear 55 | // > 0 : Clockwise 56 | fun orientation(p: Point, q: Point, r: Point): Int { 57 | return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y) 58 | } 59 | 60 | val EUCLIDEAN_DISTANCE_FUNC: (Point, Point) -> (Double) = { p, q -> 61 | val dx = p.x - q.x 62 | val dy = p.y - q.y 63 | Math.sqrt((dx * dx + dy * dy).toDouble()) 64 | } 65 | 66 | val MANHATTAN_DISTANCE_FUNC: (Point, Point) -> (Double) = { p, q -> 67 | val dx = p.x - q.x 68 | val dy = p.y - q.y 69 | Math.sqrt((dx * dx + dy * dy).toDouble()) 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/GrahamScan.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Stack 26 | import io.uuddlrlrba.ktalgs.geometry.Point 27 | 28 | class GrahamScan: ConvexHullAlgorithm { 29 | override fun convexHull(points: Array): Collection { 30 | if (points.size < 3) throw IllegalArgumentException("there must be at least 3 points") 31 | 32 | val hull = Stack() 33 | 34 | // Find the leftmost point 35 | points.sortBy { it.y } 36 | 37 | // Sort points by polar angle with p 38 | points.sortWith( Comparator { q1, q2 -> 39 | val dx1 = q1.x - points[0].x 40 | val dy1 = q1.y - points[0].y 41 | val dx2 = q2.x - points[0].x 42 | val dy2 = q2.y - points[0].y 43 | 44 | if (dy1 >= 0 && dy2 < 0) 45 | -1 // q1 above; q2 below 46 | else if (dy2 >= 0 && dy1 < 0) 47 | +1 // q1 below; q2 above 48 | else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal 49 | if (dx1 >= 0 && dx2 < 0) 50 | -1 51 | else if (dx2 >= 0 && dx1 < 0) 52 | +1 53 | else 54 | 0 55 | } else 56 | -Point.orientation(points[0], q1, q2) // both above or below 57 | // Note: ccw() recomputes dx1, dy1, dx2, and dy2 58 | }) 59 | 60 | hull.push(points[0]) 61 | hull.push(points[1]) 62 | 63 | for (i in IntRange(2, points.size - 1)) { 64 | var top = hull.poll() 65 | while (Point.orientation(hull.peek(), top, points[i]) <= 0) { 66 | top = hull.poll() 67 | } 68 | hull.push(top) 69 | hull.push(points[i]) 70 | } 71 | 72 | return hull 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/sorts/QuickSort.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.sorts 24 | 25 | /** 26 | * Developed by Tony Hoare in 1959, with his work published in 1961, Quicksort is an efficient sort algorithm using 27 | * divide and conquer approach. Quicksort first divides a large array into two smaller sub-arrays: the low elements 28 | * and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: 29 | * 1) Pick an element, called a pivot, from the array. 30 | * 2) Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, 31 | * while all elements with values greater than the pivot come after it (equal values can go either way). 32 | * After this partitioning, the pivot is in its final position. This is called the partition operation. 33 | * 3) Recursively apply the above steps to the sub-array of elements with smaller values and separately to 34 | * the sub-array of elements with greater values. 35 | */ 36 | @ComparisonSort 37 | @UnstableSort 38 | class QuickSort: AbstractSortStrategy() { 39 | override fun > perform(arr: Array) { 40 | sort(arr, 0, arr.size - 1) 41 | } 42 | 43 | private fun > sort(arr: Array, lo: Int, hi: Int) { 44 | if (hi <= lo) return 45 | val j = partition(arr, lo, hi) 46 | sort(arr, lo, j - 1) 47 | sort(arr, j + 1, hi) 48 | } 49 | 50 | private fun > partition(arr: Array, lo: Int, hi: Int): Int { 51 | var i = lo 52 | var j = hi + 1 53 | val v = arr[lo] 54 | while (true) { 55 | while (arr[++i] < v) { 56 | if (i == hi) break 57 | } 58 | while (v < arr[--j]) { 59 | if (j == lo) break 60 | } 61 | if (j <= i) break 62 | arr.exch(j, i) 63 | } 64 | arr.exch(j, lo) 65 | return j 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/Stack.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import java.util.* 26 | 27 | @Suppress("RedundantVisibilityModifier") 28 | public class Stack : Collection { 29 | private var head: Node? = null 30 | public override var size: Int = 0 31 | private set 32 | 33 | private class Node(var value: T) { 34 | var next: Node? = null 35 | } 36 | 37 | public fun push(item: T) { 38 | val new = Node(item) 39 | new.next = head 40 | head = new 41 | size++ 42 | } 43 | 44 | public fun peek(): T { 45 | if (size == 0) throw NoSuchElementException() 46 | return head!!.value 47 | } 48 | 49 | public fun poll(): T { 50 | if (size == 0) throw NoSuchElementException() 51 | val old = head!! 52 | head = old.next 53 | size-- 54 | return old.value 55 | } 56 | 57 | public override fun isEmpty(): Boolean { 58 | return size == 0 59 | } 60 | 61 | public override fun contains(element: T): Boolean { 62 | for (obj in this) { 63 | if (obj == element) return true 64 | } 65 | return false 66 | } 67 | 68 | public override fun containsAll(elements: Collection): Boolean { 69 | for (element in elements) { 70 | if (!contains(element)) return false 71 | } 72 | return true 73 | } 74 | 75 | public override fun iterator(): Iterator { 76 | return object : Iterator { 77 | var node = head 78 | 79 | override fun hasNext(): Boolean { 80 | return node != null 81 | } 82 | 83 | override fun next(): T { 84 | if (!hasNext()) throw NoSuchElementException() 85 | val current = node!! 86 | node = current.next 87 | return current.value 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/GiftWrapping.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Stack 26 | import io.uuddlrlrba.ktalgs.geometry.Point 27 | 28 | class GiftWrapping: ConvexHullAlgorithm { 29 | override fun convexHull(points: Array): Collection { 30 | if (points.size < 3) throw IllegalArgumentException("there must be at least 3 points") 31 | 32 | val hull = Stack() 33 | 34 | // Find the leftmost point 35 | var l = 0 36 | points.indices 37 | .asSequence() 38 | .filter { points[it].x < points[l].x } 39 | .forEach { l = it } 40 | 41 | // Start from leftmost point, keep moving counterclockwise 42 | // until reach the start point again. This loop runs O(h) 43 | // times where h is number of points in result or output. 44 | var p = l 45 | var q: Int 46 | do { 47 | // Add current point to result 48 | hull.push(points[p]) 49 | 50 | // Search for a point 'q' such that orientation(p, x, 51 | // q) is counterclockwise for all points 'x'. The idea 52 | // is to keep track of last visited most counterclock- 53 | // wise point in q. If any point 'i' is more counterclock- 54 | // wise than q, then update q. 55 | q = ( p+ 1) % points.size 56 | points.indices 57 | .asSequence() 58 | .filter { Point.orientation(points[p], points[it], points[q]) < 0 } 59 | .forEach { q = it } 60 | 61 | // Now q is the most counterclockwise with respect to p 62 | // Set p as q for next iteration, so that q is added to 63 | // result 'hull' 64 | p = q 65 | 66 | } while (p != l) // While we don't come to first point 67 | 68 | return hull 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/BoruvkaMST.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.DisjointSet 26 | import io.uuddlrlrba.ktalgs.datastructures.Queue 27 | 28 | class BoruvkaMST(G: UWGraph): MST { 29 | var weight: Double = 0.0 30 | var edges: Queue = Queue() 31 | 32 | init { 33 | val uf = DisjointSet(G.V) 34 | 35 | // repeat at most log V times or until we have V-1 edges 36 | var t = 1 37 | while (t < G.V && edges.size < G.V - 1) { 38 | 39 | // foreach tree in forest, find closest edge 40 | // if edge weights are equal, ties are broken in favor of first edge in G.edges() 41 | val closest = arrayOfNulls(G.V) 42 | for (e in G.edges()) { 43 | val v = e.v 44 | val w = e.w 45 | val i = uf.find(v) 46 | val j = uf.find(w) 47 | if (i == j) continue // same tree 48 | if (closest[i] == null || e < closest[i]!!) closest[i] = e 49 | if (closest[j] == null || e < closest[j]!!) closest[j] = e 50 | } 51 | 52 | // add newly discovered edges to MST 53 | for (i in 0 until G.V) { 54 | val e = closest[i] 55 | if (e != null) { 56 | val v = e.v 57 | val w = e.w 58 | // don't add the same edge twice 59 | if (!uf.connected(v, w)) { 60 | edges.add(e) 61 | weight += e.weight 62 | uf.union(v, w) 63 | } 64 | } 65 | } 66 | t += t 67 | } 68 | } 69 | 70 | override fun edges(): Iterable { 71 | return edges 72 | } 73 | 74 | override fun weight(): Double { 75 | return weight 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/search/AbstractSearchTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.search 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | abstract class AbstractSearchTest>(val strategy: T) { 29 | @Test 30 | fun emptyTest() { 31 | Assert.assertEquals(-1, strategy.perform(emptyArray(), 1)) 32 | } 33 | 34 | @Test 35 | fun singletonTest() { 36 | Assert.assertEquals(0, strategy.perform(arrayOf(1), 1)) 37 | Assert.assertEquals(-1, strategy.perform(arrayOf(1), 2)) 38 | } 39 | 40 | @Test 41 | fun twoElementsTest() { 42 | Assert.assertEquals(0, strategy.perform(arrayOf(1, 2), 1)) 43 | Assert.assertEquals(1, strategy.perform(arrayOf(1, 2), 2)) 44 | Assert.assertEquals(-1, strategy.perform(arrayOf(1, 2), 3)) 45 | } 46 | 47 | @Test 48 | fun tenElementsTest() { 49 | Assert.assertEquals(0, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 1)) 50 | Assert.assertEquals(1, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 2)) 51 | Assert.assertEquals(2, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 3)) 52 | Assert.assertEquals(3, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 4)) 53 | Assert.assertEquals(4, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 5)) 54 | Assert.assertEquals(5, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 6)) 55 | Assert.assertEquals(6, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 7)) 56 | Assert.assertEquals(7, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 8)) 57 | Assert.assertEquals(8, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 9)) 58 | Assert.assertEquals(9, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 10)) 59 | Assert.assertEquals(-1, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 0)) 60 | Assert.assertEquals(-1, strategy.perform(arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 11)) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/Queue.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import java.util.* 26 | 27 | @Suppress("RedundantVisibilityModifier") 28 | public class Queue : Collection { 29 | private var head: Node? = null 30 | private var tail: Node? = null 31 | public override var size: Int = 0 32 | private set 33 | 34 | private class Node(var value: T) { 35 | var next: Node? = null 36 | } 37 | 38 | public fun add(item: T) { 39 | val new = Node(item) 40 | val tail = this.tail 41 | if (tail == null) { 42 | head = new 43 | this.tail = new 44 | } else { 45 | tail.next = new 46 | this.tail = new 47 | } 48 | size++ 49 | } 50 | 51 | public fun peek(): T { 52 | if (size == 0) throw NoSuchElementException() 53 | return head!!.value 54 | } 55 | 56 | public fun poll(): T { 57 | if (size == 0) throw NoSuchElementException() 58 | val old = head!! 59 | head = old.next 60 | size-- 61 | return old.value 62 | } 63 | 64 | public override fun isEmpty(): Boolean { 65 | return size == 0 66 | } 67 | 68 | public override fun contains(element: T): Boolean { 69 | for (obj in this) { 70 | if (obj == element) return true 71 | } 72 | return false 73 | } 74 | 75 | public override fun containsAll(elements: Collection): Boolean { 76 | for (element in elements) { 77 | if (!contains(element)) return false 78 | } 79 | return true 80 | } 81 | 82 | public override fun iterator(): Iterator { 83 | return object : Iterator { 84 | var node = head 85 | 86 | override fun hasNext(): Boolean { 87 | return node != null 88 | } 89 | 90 | override fun next(): T { 91 | if (!hasNext()) throw NoSuchElementException() 92 | val current = node!! 93 | node = current.next 94 | return current.value 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/PrimMST.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.IndexedPriorityQueue 26 | import io.uuddlrlrba.ktalgs.datastructures.Queue 27 | 28 | class PrimMST(G: UWGraph): MST { 29 | var weight: Double = 0.0 30 | var edges: Queue = Queue() 31 | 32 | /** 33 | * distTo[v] = distance of shortest s->v path 34 | */ 35 | private val distTo: DoubleArray = DoubleArray(G.V) { Double.POSITIVE_INFINITY } 36 | 37 | /** 38 | * edgeTo[v] = last edge on shortest s->v path 39 | */ 40 | private val edgeTo: Array = arrayOfNulls(G.V) 41 | 42 | /** 43 | * priority queue of vertices 44 | */ 45 | private val pq: IndexedPriorityQueue = IndexedPriorityQueue(G.V) 46 | 47 | private val visited = Array(G.V) { false } 48 | 49 | init { 50 | for (s in G.vertices()) { 51 | if (!visited[s]) { 52 | distTo[s] = 0.0 53 | pq.insert(s, 0.0) 54 | while (!pq.isEmpty()) { 55 | val v = pq.poll().first 56 | visited[v] = true 57 | for (e in G.adjacentEdges(v)) { 58 | scan(e, v) 59 | } 60 | } 61 | } 62 | } 63 | 64 | for (v in edgeTo.indices) { 65 | val e = edgeTo[v] 66 | if (e != null) { 67 | edges.add(e) 68 | weight += e.weight 69 | } 70 | } 71 | } 72 | 73 | private fun scan(e: UWGraph.Edge, v: Int) { 74 | val w = e.other(v) 75 | if (!visited[w]) { // v-w is obsolete edge 76 | if (e.weight < distTo[w]) { 77 | distTo[w] = e.weight 78 | edgeTo[w] = e 79 | if (pq.contains(w)) { 80 | pq.decreaseKey(w, distTo[w]) 81 | } else { 82 | pq.insert(w, distTo[w]) 83 | } 84 | } 85 | } 86 | } 87 | 88 | override fun edges(): Iterable { 89 | return edges 90 | } 91 | 92 | override fun weight(): Double { 93 | return weight 94 | } 95 | } -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/DFS.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Stack 26 | 27 | class DFS { 28 | companion object Implementations { 29 | fun iterative(graph: Graph, 30 | preorder: ((Int) -> Unit)? = null, 31 | postorder: ((Int) -> Unit)? = null) { 32 | val visited = IntArray(graph.V) 33 | val queue = Stack() 34 | for (i in 0 until graph.V) { 35 | if (visited[i] == 0) { 36 | queue.push(i) 37 | visited[i] = 1 38 | while (!queue.isEmpty()) { 39 | val v = queue.poll() 40 | if (visited[v] == 1) { 41 | visited[i] = 2 42 | preorder?.invoke(i) 43 | queue.push(v) 44 | for (w in graph.adjacentVertices(v)) { 45 | if (visited[w] == 0) { 46 | queue.push(w) 47 | visited[w] = 1 48 | } 49 | } 50 | } else { 51 | visited[i] = 3 52 | postorder?.invoke(i) 53 | } 54 | } 55 | } 56 | } 57 | } 58 | 59 | fun recursive(graph: Graph, 60 | preorder: ((Int) -> Unit)? = null, 61 | postorder: ((Int) -> Unit)? = null) { 62 | val visited = BooleanArray(graph.V) 63 | for (i in 0..graph.V - 1) { 64 | if (!visited[i]) { 65 | dfs(i, graph, visited, preorder, postorder) 66 | } 67 | } 68 | } 69 | 70 | private fun dfs(v: Int, graph: Graph, visited: BooleanArray, 71 | preorder: ((Int) -> Unit)? = null, 72 | postorder: ((Int) -> Unit)? = null) { 73 | visited[v] = true 74 | preorder?.invoke(v) 75 | for (w in graph.adjacentVertices(v)) { 76 | if (!visited[w]) { 77 | dfs(w, graph, visited, preorder, postorder) 78 | } 79 | } 80 | postorder?.invoke(v) 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/MSTTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.undirected.weighted 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | import java.net.URL 28 | import java.util.* 29 | 30 | abstract class MSTTest(val strategy: (UWGraph) -> (MST)) { 31 | @Test 32 | fun test1() { 33 | val graph = UWGraph(4) 34 | graph.addEdge(0, 1, 4.0) 35 | graph.addEdge(1, 2, 1.0) 36 | graph.addEdge(2, 3, 2.0) 37 | graph.addEdge(0, 3, 5.0) 38 | graph.addEdge(0, 1, 4.0) 39 | graph.addEdge(1, 3, 3.0) 40 | val mst = strategy(graph) 41 | Assert.assertEquals(7.0, mst.weight(), 1e-12) 42 | } 43 | 44 | @Test 45 | fun test2() { 46 | val graph = UWGraph(5) 47 | graph.addEdge(0, 1, 4.0) 48 | graph.addEdge(1, 2, 1.0) 49 | graph.addEdge(2, 3, 7.0) 50 | graph.addEdge(3, 4, 6.0) 51 | graph.addEdge(0, 4, 2.0) 52 | graph.addEdge(1, 4, 3.0) 53 | graph.addEdge(1, 3, 5.0) 54 | val mst = strategy(graph) 55 | Assert.assertEquals(11.0, mst.weight(), 1e-12) 56 | } 57 | 58 | @Test 59 | fun test3() { 60 | val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/tinyEWG.txt")) 61 | val mst = strategy(graph) 62 | Assert.assertEquals(1.81, mst.weight(), 1e-12) 63 | } 64 | 65 | @Test 66 | fun test4() { 67 | val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/mediumEWG.txt")) 68 | val mst = strategy(graph) 69 | Assert.assertEquals(10.46351, mst.weight(), 1e-12) 70 | } 71 | 72 | @Test 73 | fun test5() { 74 | val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/1000EWG.txt")) 75 | val mst = strategy(graph) 76 | Assert.assertEquals(20.77320, mst.weight(), 1e-12) 77 | } 78 | 79 | @Test 80 | fun test6() { 81 | val graph = readFromURL(URL("https://algs4.cs.princeton.edu/43mst/10000EWG.txt")) 82 | val mst = strategy(graph) 83 | Assert.assertEquals(65.24072, mst.weight(), 1e-12) 84 | } 85 | 86 | fun readFromURL(url: URL): UWGraph { 87 | Scanner(url.openStream()).useLocale(Locale.US).use { scanner -> 88 | val graph = UWGraph(scanner.nextInt()) 89 | for (i in 0 until scanner.nextInt()) { 90 | graph.addEdge(scanner.nextInt(), scanner.nextInt(), scanner.nextDouble()) 91 | } 92 | scanner.close() 93 | return graph 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/geometry/QuadTree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry 24 | 25 | class QuadNode private constructor( 26 | private val NW: QuadTree, 27 | private val NE: QuadTree, 28 | private val SW: QuadTree, 29 | private val SE: QuadTree) : QuadTree { 30 | override val frame: Rect = Rect(NW.frame.TL, SE.frame.BR) 31 | 32 | constructor(frame: Rect) : this( 33 | QuadNil(Rect(frame.origin, frame.width / 2, frame.height / 2)), 34 | QuadNil(Rect(Point(frame.x1 + frame.width / 2 + 1, frame.y1), frame.width / 2, frame.height / 2)), 35 | QuadNil(Rect(Point(frame.x1, frame.y1 + frame.height / 2 + 1), frame.width / 2, frame.height / 2)), 36 | QuadNil(Rect(frame.center, frame.width / 2, frame.height / 2)) 37 | ) 38 | 39 | override fun get(rect: Rect): Iterable = 40 | (if (NW.frame.intersects(rect)) NW[rect] else emptyList()) + 41 | (if (NE.frame.intersects(rect)) NE[rect] else emptyList()) + 42 | (if (SW.frame.intersects(rect)) SW[rect] else emptyList()) + 43 | (if (SE.frame.intersects(rect)) SE[rect] else emptyList()) 44 | 45 | 46 | override fun plus(pair: Pair): QuadTree = QuadNode( 47 | if (NW.frame.isInside(pair.first)) NW + pair else NW, 48 | if (NE.frame.isInside(pair.first)) NE + pair else NE, 49 | if (SW.frame.isInside(pair.first)) SW + pair else SW, 50 | if (SE.frame.isInside(pair.first)) SE + pair else SE 51 | ) 52 | } 53 | 54 | class QuadLeaf(override val frame: Rect, val value: Pair) : QuadTree { 55 | override fun get(rect: Rect): Iterable = 56 | if (rect.isInside(value.first)) listOf(value.second) 57 | else emptyList() 58 | override fun plus(pair: Pair): QuadTree = QuadNode(frame.cover(pair.first)) + value + pair 59 | } 60 | 61 | class QuadNil(override val frame: Rect) : QuadTree { 62 | override fun get(rect: Rect): Iterable = emptyList() 63 | override fun plus(pair: Pair): QuadLeaf = QuadLeaf(frame.cover(pair.first), value = pair) 64 | } 65 | 66 | interface QuadTree { 67 | val frame: Rect 68 | operator fun get(rect: Rect): Iterable 69 | operator fun plus(pair: Pair): QuadTree 70 | } 71 | 72 | fun emptyQuadTree(frame: Rect): QuadTree = QuadNil(frame) 73 | fun quadTreeOf(frame: Rect, vararg pairs: Pair): QuadTree { 74 | var empty = emptyQuadTree(frame) 75 | for (pair in pairs) { 76 | empty += pair 77 | } 78 | return empty 79 | } 80 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/Dequeue.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import java.util.* 26 | 27 | @Suppress("RedundantVisibilityModifier") 28 | public class Dequeue : Collection { 29 | private var head: Node? = null 30 | private var tail: Node? = null 31 | public override var size: Int = 0 32 | private set 33 | 34 | private class Node(var value: T) { 35 | var next: Node? = null 36 | } 37 | 38 | public fun add(item: T) { 39 | val new = Node(item) 40 | val tail = this.tail 41 | if (tail == null) { 42 | head = new 43 | this.tail = new 44 | } else { 45 | tail.next = new 46 | this.tail = new 47 | } 48 | size++ 49 | } 50 | 51 | public fun push(item: T) { 52 | val new = Node(item) 53 | new.next = head 54 | head = new 55 | size++ 56 | } 57 | 58 | public fun peekFirst(): T { 59 | if (size == 0) throw NoSuchElementException() 60 | return head!!.value 61 | } 62 | 63 | public fun peekLast(): T { 64 | if (size == 0) throw NoSuchElementException() 65 | return tail!!.value 66 | } 67 | 68 | public fun pollFirst(): T { 69 | if (size == 0) throw NoSuchElementException() 70 | val old = head!! 71 | head = old.next 72 | return old.value 73 | } 74 | 75 | public fun pollLast(): T { 76 | if (size == 0) throw NoSuchElementException() 77 | var node = head!! 78 | while (node.next != null && node.next != tail) { 79 | node = node.next!! 80 | } 81 | val ret = node.next!! 82 | node.next = null 83 | tail = node 84 | return ret.value 85 | } 86 | 87 | public override fun isEmpty(): Boolean { 88 | return size == 0 89 | } 90 | 91 | public override fun contains(element: T): Boolean { 92 | for (obj in this) { 93 | if (obj == element) return true 94 | } 95 | return false 96 | } 97 | 98 | public override fun containsAll(elements: Collection): Boolean { 99 | for (element in elements) { 100 | if (!contains(element)) return false 101 | } 102 | return true 103 | } 104 | 105 | public override fun iterator(): Iterator { 106 | return object : Iterator { 107 | var node = head 108 | 109 | override fun hasNext(): Boolean { 110 | return node != null 111 | } 112 | 113 | override fun next(): T { 114 | if (!hasNext()) throw NoSuchElementException() 115 | val current = node!! 116 | node = current.next 117 | return current.value 118 | } 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/geometry/convexhull/ConvexHullTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.geometry.convexhull 24 | 25 | import io.uuddlrlrba.ktalgs.geometry.Point 26 | import org.junit.Assert 27 | import org.junit.Test 28 | 29 | abstract class ConvexHullTest(val strategy: ConvexHullAlgorithm) { 30 | @Test 31 | fun test1() { 32 | val points = arrayOf( 33 | Point(1, 1), 34 | Point(2, 5), 35 | Point(3, 3), 36 | Point(5, 3), 37 | Point(3, 2), 38 | Point(2, 2) 39 | ) 40 | val expected = sortedSetOf( 41 | Point(1, 1), 42 | Point(2, 5), 43 | Point(5, 3) 44 | ) 45 | val hull = strategy.convexHull(points) 46 | Assert.assertEquals(expected, hull.toSortedSet()) 47 | } 48 | 49 | @Test 50 | fun test2() { 51 | val points = arrayOf( 52 | Point(3, 2), 53 | Point(2, 5), 54 | Point(4, 5) 55 | ) 56 | val expected = points.toSortedSet() 57 | val hull = strategy.convexHull(points) 58 | Assert.assertEquals(expected, hull.toSortedSet()) 59 | } 60 | 61 | @Test 62 | fun test3() { 63 | val points = arrayOf( 64 | Point(0, 3), 65 | Point(2, 2), 66 | Point(1, 1), 67 | Point(2, 1), 68 | Point(3, 0), 69 | Point(0, 0), 70 | Point(3, 3) 71 | ) 72 | val expected = sortedSetOf( 73 | Point(0, 3), 74 | Point(3, 0), 75 | Point(0, 0), 76 | Point(3, 3) 77 | ) 78 | val hull = strategy.convexHull(points) 79 | Assert.assertEquals(expected, hull.toSortedSet()) 80 | } 81 | 82 | @Test 83 | fun test4() { 84 | val expected = arrayOf( 85 | Point(10, 3), 86 | Point(8, 0), 87 | Point(2, 0), 88 | Point(0, 3), 89 | Point(2, 6), 90 | Point(8, 6) 91 | ) 92 | val points = expected + arrayOf( 93 | Point(3, 5), 94 | Point(3, 3), 95 | Point(6, 3), 96 | Point(6, 3), 97 | Point(7, 1), 98 | Point(8, 4) 99 | ) 100 | val hull = strategy.convexHull(points) 101 | Assert.assertEquals(expected.toSortedSet(), hull.toSortedSet()) 102 | } 103 | 104 | @Test(expected= IllegalArgumentException::class) 105 | fun exceptionTest0() { 106 | strategy.convexHull(emptyArray()) 107 | } 108 | 109 | @Test(expected= IllegalArgumentException::class) 110 | fun exceptionTest1() { 111 | strategy.convexHull(arrayOf(Point(0, 0))) 112 | } 113 | 114 | @Test(expected= IllegalArgumentException::class) 115 | fun exceptionTest2() { 116 | strategy.convexHull(arrayOf(Point(0, 0), Point(1, 1))) 117 | } 118 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![alt text](kotlin-algorithm-club.png "Logo Title Text 1") 2 | 3 | [![Kotlin](https://img.shields.io/badge/kotlin-1.2.41-blue.svg)](http://kotlinlang.org) 4 | [![License](https://img.shields.io/github/license/bmaslakov/kotlin-algorithm-club.svg)](LICENSE) 5 | [![codebeat badge](https://codebeat.co/badges/9a90c6ce-eb29-4cd3-9e92-ed64181784dc)](https://codebeat.co/projects/github-com-bmaslakov-kotlin-algorithm-club-master) 6 | 7 | Here you can find the most common algorithms and data structures written in Kotlin. 8 | 9 | The goal of this project is to create the most eloquent implementations of old algorithms in the new language. The code is meant to be as self-describing as possible, so I do not plan to include much documentation. It is assumed that you know the basics; if you want to learn algorithms perhaps it is a wrong place. I do full-heartedly recommend [The Algorithm Design Manual by Steven Skiena](https://www.amazon.com/Algorithm-Design-Manual-Steven-Skiena/dp/1848000693) and of course... 10 | 11 | ## [Algorithms, 4th Edition](http://algs4.cs.princeton.edu/home/) 12 | 13 | This project is inspired by and based on wonderful works of [Robert Sedgewick](http://www.cs.princeton.edu/~rs/) and [Kevin Wayne](http://www.cs.princeton.edu/~wayne/contact/). Most of the implementations were taken from the [algs4](https://github.com/kevin-wayne/algs4) library. 14 | 15 | ## List of the algorithms 16 | 17 | ##### Sorting 18 | 19 | - [Insertion Sort](src/main/io/uuddlrlrba/ktalgs/sorts/InsertionSort.kt) 20 | - [Selection Sort](src/main/io/uuddlrlrba/ktalgs/sorts/SelectionSort.kt) 21 | - [Bubble Sort](src/main/io/uuddlrlrba/ktalgs/sorts/BubbleSort.kt) 22 | - [Merge Sort](src/main/io/uuddlrlrba/ktalgs/sorts/MergeSort.kt) 23 | - [Quick Sort](src/main/io/uuddlrlrba/ktalgs/sorts/QuickSort.kt) 24 | - [Shell Sort](src/main/io/uuddlrlrba/ktalgs/sorts/ShellSort.kt) 25 | - [Heap Sort](src/main/io/uuddlrlrba/ktalgs/sorts/HeapSort.kt) 26 | 27 | ##### Data Structures 28 | 29 | - [Queue](src/main/io/uuddlrlrba/ktalgs/datastructures/Queue.kt) 30 | - [Stack](src/main/io/uuddlrlrba/ktalgs/datastructures/Stack.kt) 31 | - [Dequeue](src/main/io/uuddlrlrba/ktalgs/datastructures/Dequeue.kt) 32 | - [Priority Queue](src/main/io/uuddlrlrba/ktalgs/datastructures/PriorityQueue.kt) 33 | - [Indexed Priority Queue](src/main/io/uuddlrlrba/ktalgs/datastructures/IndexedPriorityQueue.kt) 34 | - [Disjoint Set (Union Find)](src/main/io/uuddlrlrba/ktalgs/datastructures/DisjointSet.kt) 35 | - [Tree](src/main/io/uuddlrlrba/ktalgs/datastructures/tree/Tree.kt) 36 | - [Binary Tree](src/main/io/uuddlrlrba/ktalgs/datastructures/tree/BinaryTree.kt) 37 | - [Binary Search Tree](src/main/io/uuddlrlrba/ktalgs/datastructures/tree/BinarySearchTree.kt) 38 | - [Immutable Set (based on binary search)](src/main/io/uuddlrlrba/ktalgs/datastructures/tree/ImmutableSet.kt) 39 | 40 | ##### Search 41 | 42 | - [Linear Search](src/main/io/uuddlrlrba/ktalgs/search/LinearSearch.kt) 43 | - [Binary Search](src/main/io/uuddlrlrba/ktalgs/search/BinarySearch.kt) 44 | 45 | ##### Graphs 46 | 47 | - [Breadth First Search](src/main/io/uuddlrlrba/ktalgs/graphs/BFS.kt) 48 | - [Depth First Search](src/main/io/uuddlrlrba/ktalgs/graphs/DFS.kt) 49 | - [Kruskal's minimum spanning tree](src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/KruskalMST.kt) 50 | - [Prim's minimum spanning tree](src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/PrimMST.kt) 51 | - [Boruvka's minimum spanning tree](src/main/io/uuddlrlrba/ktalgs/graphs/undirected/weighted/BoruvkaMST.kt) 52 | - [Dijkstra's shortest paths](src/main/io/uuddlrlrba/ktalgs/graphs/directed/weighted/Dijkstra.kt) 53 | 54 | ##### Math 55 | 56 | - [GCD / LCM](src/main/io/uuddlrlrba/ktalgs/math/Gcd.kt) 57 | - [Newton Method](src/main/io/uuddlrlrba/ktalgs/math/NewtonMethod.kt) 58 | - [Binomial](src/main/io/uuddlrlrba/ktalgs/math/Binomial.kt) 59 | 60 | ##### Geometry 61 | 62 | - [Gift wrapping (Jarvis)](src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/GiftWrapping.kt) 63 | - [Graham Scan](src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/GrahamScan.kt) 64 | - [Quickhull](src/main/io/uuddlrlrba/ktalgs/geometry/convexhull/Quickhull.kt) 65 | - [Voronoi Diagram (Naïve implementation)](src/main/io/uuddlrlrba/ktalgs/geometry/Voronoi.kt) 66 | - [Sierpinski triangle](src/main/io/uuddlrlrba/ktalgs/geometry/SierpinskiTriangle.kt) 67 | 68 | ##### Substring search 69 | 70 | - [Knuth–Morris–Pratt (KMP)](src/main/io/uuddlrlrba/ktalgs/substring/KMP.kt) 71 | 72 | ## License 73 | 74 | Kotlin algorithm club is released under the [MIT License](https://opensource.org/licenses/MIT). 75 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/graphs/directed/weighted/Dijkstra.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.graphs.directed.weighted 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.IndexedPriorityQueue 26 | import io.uuddlrlrba.ktalgs.datastructures.Stack 27 | import io.uuddlrlrba.ktalgs.graphs.NoSuchPathException 28 | 29 | class Dijkstra(graph: DWGraph, val from: Int) { 30 | /** 31 | * distTo[v] = distance of shortest s->v path 32 | */ 33 | private val distTo: DoubleArray = DoubleArray(graph.V, { if (it == from) 0.0 else Double.POSITIVE_INFINITY }) 34 | 35 | /** 36 | * edgeTo[v] = last edge on shortest s->v path 37 | */ 38 | private val edgeTo: Array = arrayOfNulls(graph.V) 39 | 40 | /** 41 | * priority queue of vertices 42 | */ 43 | private val pq: IndexedPriorityQueue = IndexedPriorityQueue(graph.V) 44 | 45 | init { 46 | if (graph.edges().any { it.weight < 0 }) { 47 | throw IllegalArgumentException("there is a negative weight edge") 48 | } 49 | 50 | // relax vertices in order of distance from s 51 | pq.insert(from, distTo[from]) 52 | while (!pq.isEmpty()) { 53 | val v = pq.poll().first 54 | for (e in graph.adjacentEdges(v)) { 55 | relax(e) 56 | } 57 | } 58 | } 59 | 60 | // relax edge e and update pq if changed 61 | private fun relax(e: DWGraph.Edge) { 62 | val v = e.from 63 | val w = e.to 64 | if (distTo[w] > distTo[v] + e.weight) { 65 | distTo[w] = distTo[v] + e.weight 66 | edgeTo[w] = e 67 | if (pq.contains(w)) { 68 | pq.decreaseKey(w, distTo[w]) 69 | } else { 70 | pq.insert(w, distTo[w]) 71 | } 72 | } 73 | } 74 | 75 | /** 76 | * Returns the length of a shortest path from the source vertex `s` to vertex `v`. 77 | * @param v the destination vertex 78 | * @return the length of a shortest path from the source vertex `s` to vertex `v`; 79 | * `Double.POSITIVE_INFINITY` if no such path 80 | */ 81 | fun distTo(v: Int): Double { 82 | return distTo[v] 83 | } 84 | 85 | /** 86 | * Returns true if there is a path from the source vertex `s` to vertex `v`. 87 | * @param v the destination vertex 88 | * @return `true` if there is a path from the source vertex 89 | * `s` to vertex `v`; `false` otherwise 90 | */ 91 | fun hasPathTo(v: Int): Boolean { 92 | return distTo[v] < java.lang.Double.POSITIVE_INFINITY 93 | } 94 | 95 | /** 96 | * Returns a shortest path from the source vertex `s` to vertex `v`. 97 | * @param v the destination vertex 98 | * @return a shortest path from the source vertex `s` to vertex `v` 99 | * as an iterable of edges, and `null` if no such path 100 | */ 101 | fun pathTo(v: Int): Iterable { 102 | if (!hasPathTo(v)) throw NoSuchPathException("There is no path from [$from] to [$v]") 103 | val path = Stack() 104 | var e = edgeTo[v] 105 | while (e != null) { 106 | path.push(e) 107 | e = edgeTo[e.from] 108 | } 109 | return path 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/PriorityQueue.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import io.uuddlrlrba.ktalgs.sorts.exch 26 | import java.util.* 27 | import kotlin.Comparator 28 | 29 | class PriorityQueue(size: Int, val comparator: Comparator? = null) : Collection { 30 | public override var size: Int = 0 31 | private set 32 | private var arr: Array = Array?>(size, { null }) as Array 33 | 34 | public fun add(element: T) { 35 | if (size + 1 == arr.size) { 36 | resize() 37 | } 38 | arr[++size] = element 39 | swim(size) 40 | } 41 | 42 | public fun peek(): T { 43 | if (size == 0) throw NoSuchElementException() 44 | return arr[1]!! 45 | } 46 | 47 | public fun poll(): T { 48 | if (size == 0) throw NoSuchElementException() 49 | val res = peek() 50 | arr.exch(1, size--) 51 | sink(1) 52 | arr[size + 1] = null 53 | if ((size > 0) && (size == (arr.size - 1) / 4)) { 54 | resize() 55 | } 56 | return res 57 | } 58 | 59 | private fun swim(n: Int) { 60 | Companion.swim(arr, n, comparator) 61 | } 62 | 63 | private fun sink(n: Int) { 64 | Companion.sink(arr, n, size, comparator) 65 | } 66 | 67 | private fun resize() { 68 | val old = arr 69 | arr = Array?>(size * 2, { null }) as Array 70 | System.arraycopy(old, 0, arr, 0, size + 1) 71 | } 72 | 73 | public override fun isEmpty(): Boolean { 74 | return size == 0 75 | } 76 | 77 | override fun contains(element: T): Boolean { 78 | for (obj in this) { 79 | if (obj == element) return true 80 | } 81 | return false 82 | } 83 | 84 | override fun containsAll(elements: Collection): Boolean { 85 | for (element in elements) { 86 | if (!contains(element)) return false 87 | } 88 | return true 89 | } 90 | 91 | override fun iterator(): Iterator { 92 | return arr.copyOfRange(1, size + 1).map { it!! }.iterator() 93 | } 94 | 95 | companion object { 96 | private fun greater(arr: Array, i: Int, j: Int, comparator: Comparator? = null): Boolean { 97 | if (comparator != null) { 98 | return comparator.compare(arr[i], arr[j]) > 0 99 | } else { 100 | val left = arr[i]!! as Comparable 101 | return left > arr[j]!! 102 | } 103 | } 104 | 105 | public fun sink(arr: Array, a: Int, size: Int, comparator: Comparator? = null) { 106 | var k = a 107 | while (2 * k <= size) { 108 | var j = 2 * k 109 | if (j < size && greater(arr, j, j + 1, comparator)) j++ 110 | if (!greater(arr, k, j, comparator)) break 111 | arr.exch(k, j) 112 | k = j 113 | } 114 | } 115 | 116 | public fun swim(arr: Array, size: Int, comparator: Comparator? = null) { 117 | var n = size 118 | while (n > 1 && greater(arr, n / 2, n, comparator)) { 119 | arr.exch(n, n / 2) 120 | n /= 2 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/tree/BinarySearchTree.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures.tree 24 | 25 | import io.uuddlrlrba.ktalgs.datastructures.Queue 26 | import java.util.NoSuchElementException 27 | 28 | class BinarySearchTree, V>: Map { 29 | data class Node( 30 | override val key: K, 31 | override var value: V, 32 | var left: Node? = null, 33 | var right: Node? = null, 34 | var size: Int = 1): Map.Entry 35 | 36 | private var root: Node? = null 37 | 38 | override val size: Int 39 | get() = size(root) 40 | 41 | override val entries: Set> 42 | get() { 43 | val set = mutableSetOf>() 44 | inorder(root) { set.add(it.copy()) } 45 | return set 46 | } 47 | 48 | override val keys: Set 49 | get() { 50 | val set = mutableSetOf() 51 | inorder(root) { set.add(it.key) } 52 | return set 53 | } 54 | 55 | override val values: Collection 56 | get() { 57 | val queue = Queue() 58 | inorder(root) { queue.add(it.value) } 59 | return queue 60 | } 61 | 62 | override fun get(key: K): V? { 63 | var x = root 64 | while (x != null) { 65 | x = when { 66 | key < x.key -> x.left 67 | key > x.key -> x.right 68 | else -> return x.value 69 | } 70 | } 71 | return null 72 | } 73 | 74 | override fun containsKey(key: K): Boolean { 75 | return get(key) != null 76 | } 77 | 78 | override fun containsValue(value: V): Boolean { 79 | return any { it.value == value } 80 | } 81 | 82 | fun add(key: K, value: V) { 83 | root = add(key, value, root) 84 | } 85 | 86 | private fun add(key: K, value: V, x: Node?): Node { 87 | if (x == null) return Node(key, value) 88 | when { 89 | key < x.key -> x.left = add(key, value, x.left) 90 | key > x.key -> x.right = add(key, value, x.right) 91 | else -> x.value = value 92 | } 93 | x.size = size(x.left) + size(x.right) + 1 94 | return x 95 | } 96 | 97 | fun remove(key: K) { 98 | root = remove(key, root) 99 | } 100 | 101 | private fun remove(key: K, root: Node?): Node? { 102 | var x: Node = root ?: throw NoSuchElementException() 103 | when { 104 | key < x.key -> x.left = remove(key, x.left) 105 | key > x.key -> x.right = remove(key, x.right) 106 | else -> { 107 | if (x.left == null) return x.right 108 | if (x.right == null) return x.left 109 | val tmp = x 110 | x = pollMin(tmp.right!!)!! 111 | x.right = min(tmp.right) 112 | x.left = tmp.left 113 | } 114 | } 115 | x.size = size(x.left) + size(x.right) + 1 116 | return x 117 | } 118 | 119 | private fun size(x: Node?): Int = x?.size ?: 0 120 | 121 | fun height(): Int { 122 | return height(root) 123 | } 124 | 125 | private fun height(x: Node?): Int { 126 | if (x == null) return 0 127 | return maxOf(height(x.left), height(x.right)) + 1 128 | } 129 | 130 | override fun isEmpty(): Boolean { 131 | return size == 0 132 | } 133 | 134 | fun min(): K { 135 | return min(root).key 136 | } 137 | 138 | fun min(node: Node?): Node { 139 | if (node == null) throw NoSuchElementException() 140 | var x: Node = node 141 | while (x.left != null) { 142 | x = x.left!! 143 | } 144 | return x 145 | } 146 | 147 | fun max(): K { 148 | return max(root).key 149 | } 150 | 151 | fun max(node: Node?): Node { 152 | if (node == null) throw NoSuchElementException() 153 | var x: Node = node 154 | while (x.right != null) { 155 | x = x.right!! 156 | } 157 | return x 158 | } 159 | 160 | fun pollMin() { 161 | if (root == null) throw NoSuchElementException() 162 | root = pollMin(root!!) 163 | } 164 | 165 | private fun pollMin(x: Node): Node? { 166 | if (x.left == null) return x.right 167 | x.left = pollMin(x.left!!) 168 | x.size = size(x.left) + size(x.right) + 1 169 | return x 170 | } 171 | 172 | fun pollMax() { 173 | if (root == null) throw NoSuchElementException() 174 | root = pollMax(root!!) 175 | } 176 | 177 | private fun pollMax(x: Node): Node? { 178 | if (x.right == null) return x.left 179 | x.right = pollMax(x.right!!) 180 | x.size = size(x.left) + size(x.right) + 1 181 | return x 182 | } 183 | 184 | private fun inorder(x: Node?, lambda: (Node) -> (Unit)) { 185 | if (x == null) return 186 | inorder(x.left, lambda) 187 | lambda(x) 188 | inorder(x.right, lambda) 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /src/main/io/uuddlrlrba/ktalgs/datastructures/IndexedPriorityQueue.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures 24 | 25 | import java.util.NoSuchElementException 26 | 27 | // TODO: resize 28 | class IndexedPriorityQueue(size: Int, val comparator: Comparator? = null) : Collection { 29 | /** 30 | * maximum number of elements on PQ 31 | */ 32 | private val maxN: Int = size 33 | 34 | /** 35 | * number of elements on PQ 36 | */ 37 | public override var size: Int = 0 38 | private set 39 | 40 | /** 41 | * binary heap using 1-based indexing 42 | */ 43 | private val pq: IntArray = IntArray(size + 1) 44 | 45 | /** 46 | * inverse of pq - qp[pq[i]] = pq[qp[i]] = i 47 | */ 48 | private val qp: IntArray = IntArray(size + 1, { -1 }) 49 | 50 | /** 51 | * keys[i] = priority of i 52 | */ 53 | private val keys: Array = Array?>(size + 1, { null }) as Array 54 | 55 | /** 56 | * Associates key with index {@code i}. 57 | * 58 | * @param i an index 59 | * @param key the key to associate with index {@code i} 60 | * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN} 61 | * @throws IllegalArgumentException if there already is an item associated with index {@code i} 62 | */ 63 | public fun insert(i: Int, key: T) { 64 | if (i < 0 || i >= maxN) throw IndexOutOfBoundsException() 65 | if (contains(i)) throw IllegalArgumentException("index is already in the priority queue") 66 | size++ 67 | qp[i] = size 68 | pq[size] = i 69 | keys[i] = key 70 | swim(size) 71 | } 72 | 73 | /** 74 | * Decrease the key associated with index `i` to the specified value. 75 | * 76 | * @param i the index of the key to decrease 77 | * @param key decrease the key associated with index `i` to this key 78 | * @throws IndexOutOfBoundsException unless `0 <= i < maxN` 79 | * @throws IllegalArgumentException if `key >=` key associated with index `i` 80 | * @throws NoSuchElementException no key is associated with index `i` 81 | */ 82 | public fun decreaseKey(i: Int, key: T) { 83 | if (i < 0 || i >= maxN) throw IndexOutOfBoundsException() 84 | if (!contains(i)) throw NoSuchElementException("index is not in the priority queue") 85 | if (!greater(keys[i]!!, key)) 86 | throw IllegalArgumentException("Calling decreaseKey()" + 87 | "with given argument would not strictly decrease the key") 88 | keys[i] = key 89 | swim(qp[i]) 90 | } 91 | 92 | /** 93 | * Increase the key associated with index `i` to the specified value. 94 | * 95 | * @param i the index of the key to increase 96 | * @param key increase the key associated with index `i` to this key 97 | * @throws IndexOutOfBoundsException unless `0 <= i < maxN` 98 | * @throws IllegalArgumentException if `key <=` key associated with index `i` 99 | * @throws NoSuchElementException no key is associated with index `i` 100 | */ 101 | public fun increaseKey(i: Int, key: T) { 102 | if (i < 0 || i >= maxN) throw IndexOutOfBoundsException() 103 | if (!contains(i)) throw NoSuchElementException("index is not in the priority queue") 104 | if (!less(keys[i]!!, key)) 105 | throw IllegalArgumentException("Calling increaseKey()" + 106 | "with given argument would not strictly increase the key") 107 | keys[i] = key 108 | sink(qp[i]) 109 | } 110 | 111 | /** 112 | * Returns a minimum key. 113 | * 114 | * @return a minimum key 115 | * @throws NoSuchElementException if this priority queue is empty 116 | */ 117 | fun peek(): Pair { 118 | if (size == 0) throw NoSuchElementException("Priority queue underflow") 119 | return Pair(pq[1], keys[pq[1]]!!) 120 | } 121 | 122 | /** 123 | * Removes a minimum key and returns its associated index. 124 | * 125 | * @return an index associated with a minimum key 126 | * @throws NoSuchElementException if this priority queue is empty 127 | */ 128 | fun poll(): Pair { 129 | if (size == 0) throw NoSuchElementException("Priority queue underflow") 130 | val min = pq[1] 131 | val element = keys[min] 132 | exch(1, size--) 133 | sink(1) 134 | assert(min == pq[size + 1]) 135 | qp[min] = -1 // delete 136 | keys[min] = null // to help with garbage collection 137 | pq[size + 1] = -1 // not needed 138 | return Pair(min, element!!) 139 | } 140 | 141 | private fun less(x: T, y: T): Boolean { 142 | return if (comparator != null) { 143 | comparator.compare(x, y) < 0 144 | } else { 145 | val left = x as Comparable 146 | left < y 147 | } 148 | } 149 | 150 | private fun greater(x: T, y: T): Boolean { 151 | return if (comparator != null) { 152 | comparator.compare(x, y) > 0 153 | } else { 154 | val left = x as Comparable 155 | left > y 156 | } 157 | } 158 | 159 | private fun greater(i: Int, j: Int): Boolean { 160 | return greater(keys[pq[i]]!!, keys[pq[j]]!!) 161 | } 162 | 163 | private fun exch(i: Int, j: Int) { 164 | val swap = pq[i] 165 | pq[i] = pq[j] 166 | pq[j] = swap 167 | qp[pq[i]] = i 168 | qp[pq[j]] = j 169 | } 170 | 171 | private fun swim(n: Int) { 172 | var k = n 173 | while (k > 1 && greater(k / 2, k)) { 174 | exch(k, k / 2) 175 | k /= 2 176 | } 177 | } 178 | 179 | private fun sink(n: Int) { 180 | var k = n 181 | while (2 * k <= size) { 182 | var j = 2 * k 183 | if (j < size && greater(j, j + 1)) j++ 184 | if (!greater(k, j)) break 185 | exch(k, j) 186 | k = j 187 | } 188 | } 189 | 190 | public fun contains(i: Int): Boolean { 191 | if (i < 0 || i >= maxN) throw IndexOutOfBoundsException() 192 | return qp[i] != -1 193 | } 194 | 195 | override fun isEmpty(): Boolean { 196 | return size == 0 197 | } 198 | 199 | override fun contains(element: T): Boolean { 200 | for (obj in this) { 201 | if (obj == element) return true 202 | } 203 | return false 204 | } 205 | 206 | override fun containsAll(elements: Collection): Boolean { 207 | for (element in elements) { 208 | if (!contains(element)) return false 209 | } 210 | return true 211 | } 212 | 213 | override fun iterator(): Iterator { 214 | return keys.copyOfRange(1, size + 1).map { it!! }.iterator() 215 | } 216 | } -------------------------------------------------------------------------------- /src/test/io/uuddlrlrba/ktalgs/datastructures/tree/BinarySearchTreeTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Kotlin Algorithm Club 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package io.uuddlrlrba.ktalgs.datastructures.tree 24 | 25 | import org.junit.Assert 26 | import org.junit.Test 27 | 28 | class BinarySearchTreeTest { 29 | @Test 30 | fun empty() { 31 | val tree = BinarySearchTree() 32 | Assert.assertEquals(0, tree.size) 33 | Assert.assertTrue(tree.isEmpty()) 34 | } 35 | 36 | @Test 37 | fun sizeOfOne() { 38 | val tree = BinarySearchTree() 39 | tree.add(1, "1") 40 | Assert.assertFalse(tree.isEmpty()) 41 | Assert.assertEquals(1, tree.size) 42 | Assert.assertEquals(1, tree.height()) 43 | Assert.assertEquals(1, tree.min()) 44 | Assert.assertEquals(1, tree.max()) 45 | Assert.assertEquals("1", tree[1]) 46 | tree.pollMin() 47 | Assert.assertTrue(tree.isEmpty()) 48 | } 49 | 50 | @Test 51 | fun sizeOfThree() { 52 | val tree = BinarySearchTree() 53 | tree.add(1, "1") 54 | tree.add(2, "2") 55 | tree.add(3, "3") 56 | Assert.assertFalse(tree.isEmpty()) 57 | Assert.assertEquals(3, tree.size) 58 | Assert.assertEquals(3, tree.height()) 59 | Assert.assertEquals(1, tree.min()) 60 | Assert.assertEquals(3, tree.max()) 61 | Assert.assertEquals("1", tree[1]) 62 | Assert.assertEquals("2", tree[2]) 63 | Assert.assertEquals("3", tree[3]) 64 | tree.pollMin() 65 | Assert.assertEquals(2, tree.min()) 66 | Assert.assertEquals(3, tree.max()) 67 | Assert.assertEquals("2", tree[2]) 68 | Assert.assertEquals("3", tree[3]) 69 | tree.pollMax() 70 | Assert.assertEquals(2, tree.min()) 71 | Assert.assertEquals(2, tree.max()) 72 | Assert.assertEquals("2", tree[2]) 73 | } 74 | 75 | @Test 76 | fun overwrite() { 77 | val tree = BinarySearchTree() 78 | tree.add(1, "1") 79 | Assert.assertFalse(tree.isEmpty()) 80 | Assert.assertEquals(1, tree.size) 81 | Assert.assertEquals(1, tree.height()) 82 | Assert.assertEquals("1", tree[1]) 83 | tree.add(1, "2") 84 | Assert.assertFalse(tree.isEmpty()) 85 | Assert.assertEquals(1, tree.size) 86 | Assert.assertEquals(1, tree.height()) 87 | Assert.assertEquals(1, tree.min()) 88 | Assert.assertEquals(1, tree.max()) 89 | Assert.assertEquals("2", tree[1]) 90 | tree.pollMin() 91 | Assert.assertTrue(tree.isEmpty()) 92 | } 93 | 94 | @Test 95 | fun letters() { 96 | val tree = BinarySearchTree() 97 | val letters = arrayOf('j', 'p', 'q', 's', 'f', 'o', 'g', 'v', 'h', 'm', 'x', 'z', 98 | 'l', 'n', 'd', 'c', 'a', 'r', 'b', 't', 'i', 'u', 'w', 'k', 'y', 'e') 99 | letters.forEach { tree.add(it, it.toString()) } 100 | 101 | Assert.assertEquals(letters.toSet(), tree.keys) 102 | Assert.assertArrayEquals(letters.map { it.toString() }.sorted().toTypedArray(), 103 | tree.values.sorted().toTypedArray()) 104 | 105 | Assert.assertEquals(26, tree.size) 106 | Assert.assertEquals('a', tree.min()) 107 | Assert.assertEquals('z', tree.max()) 108 | tree.pollMin() 109 | Assert.assertEquals(25, tree.size) 110 | Assert.assertEquals('b', tree.min()) 111 | Assert.assertEquals('z', tree.max()) 112 | tree.pollMax() 113 | Assert.assertEquals(24, tree.size) 114 | Assert.assertEquals('b', tree.min()) 115 | Assert.assertEquals('y', tree.max()) 116 | tree.pollMin() 117 | Assert.assertEquals(23, tree.size) 118 | Assert.assertEquals('c', tree.min()) 119 | Assert.assertEquals('y', tree.max()) 120 | tree.pollMax() 121 | Assert.assertEquals(22, tree.size) 122 | Assert.assertEquals('c', tree.min()) 123 | Assert.assertEquals('x', tree.max()) 124 | tree.pollMin() 125 | Assert.assertEquals(21, tree.size) 126 | Assert.assertEquals('d', tree.min()) 127 | Assert.assertEquals('x', tree.max()) 128 | tree.pollMax() 129 | Assert.assertEquals(20, tree.size) 130 | Assert.assertEquals('d', tree.min()) 131 | Assert.assertEquals('w', tree.max()) 132 | tree.pollMin() 133 | tree.pollMin() 134 | tree.pollMin() 135 | Assert.assertEquals(17, tree.size) 136 | Assert.assertEquals('g', tree.min()) 137 | Assert.assertEquals('w', tree.max()) 138 | tree.pollMax() 139 | tree.pollMax() 140 | tree.pollMax() 141 | Assert.assertEquals(14, tree.size) 142 | Assert.assertEquals('g', tree.min()) 143 | Assert.assertEquals('t', tree.max()) 144 | tree.pollMin() 145 | tree.pollMin() 146 | tree.pollMin() 147 | tree.pollMin() 148 | tree.pollMin() 149 | Assert.assertEquals(9, tree.size) 150 | Assert.assertEquals('l', tree.min()) 151 | Assert.assertEquals('t', tree.max()) 152 | tree.pollMax() 153 | tree.pollMax() 154 | tree.pollMax() 155 | tree.pollMax() 156 | tree.pollMax() 157 | Assert.assertEquals(4, tree.size) 158 | Assert.assertEquals('l', tree.min()) 159 | Assert.assertEquals('o', tree.max()) 160 | tree.pollMin() 161 | Assert.assertEquals(3, tree.size) 162 | Assert.assertEquals('m', tree.min()) 163 | Assert.assertEquals('o', tree.max()) 164 | tree.pollMax() 165 | Assert.assertEquals(2, tree.size) 166 | Assert.assertEquals('m', tree.min()) 167 | Assert.assertEquals('n', tree.max()) 168 | tree.pollMin() 169 | Assert.assertEquals(1, tree.size) 170 | Assert.assertEquals('n', tree.min()) 171 | Assert.assertEquals('n', tree.max()) 172 | tree.pollMin() 173 | Assert.assertTrue(tree.isEmpty()) 174 | } 175 | 176 | @Test 177 | fun remove() { 178 | val tree = BinarySearchTree() 179 | for (i in 0..30) { 180 | tree.add(i, (i * i).toString()) 181 | } 182 | 183 | for (i in 0..30) { 184 | Assert.assertEquals((i * i).toString(), tree[i]) 185 | } 186 | 187 | var counter = 0 188 | for ((key, value) in tree) { 189 | Assert.assertEquals(counter, key) 190 | Assert.assertEquals((counter * counter).toString(), value) 191 | counter++ 192 | } 193 | 194 | tree.remove(15) 195 | tree.remove(0) 196 | tree.remove(30) 197 | Assert.assertEquals(1, tree.min()) 198 | Assert.assertEquals(29, tree.max()) 199 | tree.remove(14) 200 | tree.remove(16) 201 | tree.remove(1) 202 | tree.remove(29) 203 | Assert.assertEquals(2, tree.min()) 204 | Assert.assertEquals(28, tree.max()) 205 | tree.remove(13) 206 | tree.remove(17) 207 | tree.remove(2) 208 | tree.remove(28) 209 | Assert.assertEquals(3, tree.min()) 210 | Assert.assertEquals(27, tree.max()) 211 | tree.remove(12) 212 | tree.remove(18) 213 | tree.remove(3) 214 | tree.remove(27) 215 | Assert.assertEquals(4, tree.min()) 216 | Assert.assertEquals(26, tree.max()) 217 | tree.remove(11) 218 | tree.remove(19) 219 | tree.remove(4) 220 | tree.remove(26) 221 | Assert.assertEquals(5, tree.min()) 222 | Assert.assertEquals(25, tree.max()) 223 | Assert.assertEquals(12, tree.size) 224 | 225 | Assert.assertEquals("25", tree[5]) 226 | Assert.assertEquals("36", tree[6]) 227 | Assert.assertEquals("49", tree[7]) 228 | Assert.assertEquals("64", tree[8]) 229 | Assert.assertEquals("81", tree[9]) 230 | Assert.assertEquals("100", tree[10]) 231 | Assert.assertEquals("400", tree[20]) 232 | Assert.assertEquals("441", tree[21]) 233 | Assert.assertEquals("484", tree[22]) 234 | Assert.assertEquals("529", tree[23]) 235 | Assert.assertEquals("576", tree[24]) 236 | Assert.assertEquals("625", tree[25]) 237 | } 238 | 239 | @Test(expected= NoSuchElementException::class) 240 | fun emptyMinFails() { 241 | BinarySearchTree().min() 242 | } 243 | 244 | @Test(expected= NoSuchElementException::class) 245 | fun emptyMaxFails() { 246 | BinarySearchTree().max() 247 | } 248 | 249 | @Test(expected= NoSuchElementException::class) 250 | fun emptyPollMinFails() { 251 | BinarySearchTree().pollMin() 252 | } 253 | 254 | @Test(expected= NoSuchElementException::class) 255 | fun emptyPollMaxFails() { 256 | BinarySearchTree().pollMax() 257 | } 258 | } 259 | --------------------------------------------------------------------------------