Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de0f65c

Browse files
refactored some algorithms in the other/search packages + fixed links in the README files
1 parent 932921e commit de0f65c

23 files changed

+332
-394
lines changed

‎README.md

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -69,24 +69,23 @@ Content:
6969

7070
4. package <code>search</code> - search algorithms
7171
* [Binary search](/src/main/kotlin/search/BinarySearch.kt)
72-
* [Binary search (recursive)](/src/main/kotlin/search/BinarySearchRecursive.kt)
7372
* [Linear search](/src/main/kotlin/search/LinearSearch.kt)
7473

7574
5. package <code>other</code> - other algorithms
7675
* [Factorial](/src/main/kotlin/other/Factorial.kt)
77-
* [Knut Morris Pratt's Algorithm for finding a substring](/src/main/kotlin/other/KnuthMorrisPratt.kt)
78-
* [Levenshtein distance](/src/main/kotlin/other/LevensteinLength.kt)
79-
* [Palindrome](/src/main/kotlin/other/Palindrome.kt)
80-
* [Euclid's algorithm](/src/main/kotlin/other/Euclid.kt)
76+
* [Knut Morris Pratt's Algorithm for finding a substring](/src/main/kotlin/other/KnuthMorrisPrattAlgorithm.kt)
77+
* [Levenshtein distance](/src/main/kotlin/other/LevenshteinLengthAlgorithm.kt)
78+
* [Palindrome](/src/main/kotlin/other/PalindromeAlgorithm.kt)
79+
* [Euclid's algorithm](/src/main/kotlin/other/EuclidAlgorithm.kt)
8180
* [FizzBuzz](/src/main/kotlin/other/FizzBuzz.kt)
82-
* [Reverse Array](/src/main/kotlin/other/ReverseArray.kt)
83-
* [Sieve of Eratosthenes](/src/main/kotlin/other/SieveOfEratosthenes.kt)
84-
* [Finding the minimum](/src/main/kotlin/other/Min.kt)
85-
* [Finding the maximum](/src/main/kotlin/other/Max.kt)
81+
* [Reverse Array](/src/main/kotlin/other/ReverseArrayAlgorithm.kt)
82+
* [Sieve of Eratosthenes](/src/main/kotlin/other/SieveOfEratosthenesAlgorithm.kt)
83+
* [Finding the minimum](/src/main/kotlin/other/MinAlgorithm.kt)
84+
* [Finding the maximum](/src/main/kotlin/other/MaxAlgorithm.kt)
8685
* [The square root of a number](/src/main/kotlin/other/Sqrt.kt)
8786
* [Finite state machine](/src/main/kotlin/other/BinaryDigitsCounter.kt)
88-
* [ParenthesisCheck](/src/main/kotlin/other/ParenthesisCheck.kt)
89-
* [StringEqualsHash](/src/main/kotlin/other/StringEqualsHash.kt)
87+
* [ParenthesisCheck](/src/main/kotlin/other/ParenthesisCheckAlgorithm.kt)
88+
* [StringEqualsHash](/src/main/kotlin/other/StringEqualsHashAlgorithm.kt)
9089

9190
## Your wishes and ideas
9291

‎README_ru.md

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -69,24 +69,23 @@
6969

7070
4. пакет <code>ru.search</code> - алгоритмы поиска
7171
* [Бинарный поиск](/src/main/kotlin/search/BinarySearch.kt)
72-
* [Бинарный поиск (рекурсивный)](/src/main/kotlin/search/BinarySearchRecursive.kt)
7372
* [Линейный поиск](/src/main/kotlin/search/LinearSearch.kt)
7473

7574
5. пакет <code>ru.other</code> - другие алгоритмы
7675
* [Факториал числа](/src/main/kotlin/other/Factorial.kt)
77-
* [Алгоритм Кнута Морриса Пратта для поиска подстроки](/src/main/kotlin/other/KnuthMorrisPratt.kt)
78-
* [Расстояние Левенштейна](/src/main/kotlin/other/LevensteinLength.kt)
79-
* [Палиндром](/src/main/kotlin/other/Palindrome.kt)
80-
* [Алгоритм Эвклида](/src/main/kotlin/other/Euclid.kt)
76+
* [Алгоритм Кнута Морриса Пратта для поиска подстроки](/src/main/kotlin/other/KnuthMorrisPrattAlgorithm.kt)
77+
* [Расстояние Левенштейна](/src/main/kotlin/other/LevenshteinLengthAlgorithm.kt)
78+
* [Палиндром](/src/main/kotlin/other/PalindromeAlgorithm.kt)
79+
* [Алгоритм Эвклида](/src/main/kotlin/other/EuclidAlgorithm.kt)
8180
* [FizzBuzz](/src/main/kotlin/other/FizzBuzz.kt)
82-
* [Алгоритм переворота массива](/src/main/kotlin/other/ReverseArray.kt)
83-
* [Решето Эратосфена](/src/main/kotlin/other/SieveOfEratosthenes.kt)
84-
* [Поиск минимума](/src/main/kotlin/other/Min.kt)
85-
* [Поиск максимума](/src/main/kotlin/other/Max.kt)
81+
* [Алгоритм переворота массива](/src/main/kotlin/other/ReverseArrayAlgorithm.kt)
82+
* [Решето Эратосфена](/src/main/kotlin/other/SieveOfEratosthenesAlgorithm.kt)
83+
* [Поиск минимума](/src/main/kotlin/other/MinAlgorithm.kt)
84+
* [Поиск максимума](/src/main/kotlin/other/MaxAlgorithm.kt)
8685
* [Квадратный корень из числа](/src/main/kotlin/other/Sqrt.kt)
8786
* [Конечный автомат](/src/main/kotlin/other/BinaryDigitsCounter.kt)
88-
* [Проверка скобок на корректность](/src/main/kotlin/other/ParenthesisCheck.kt)
89-
* [Сравнение строк с помощью хэша](/src/main/kotlin/other/StringEqualsHash.kt)
87+
* [Проверка скобок на корректность](/src/main/kotlin/other/ParenthesisCheckAlgorithm.kt)
88+
* [Сравнение строк с помощью хэша](/src/main/kotlin/other/StringEqualsHashAlgorithm.kt)
9089

9190
## Ваши пожелания и идеи
9291

‎src/main/kotlin/other/FactorialBigWithCache.kt

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,17 @@ import java.math.BigInteger
1010
*
1111
* also adding large numbers
1212
*
13+
* worst time: O(n)
14+
* the best time: O(1)
15+
* amount of memory: O(n)
16+
* problem: creating a huge number of BigInteger objects
17+
*
1318
*/
1419

1520
class FactorialBigWithCache {
1621

1722
private val cache = hashMapOf<Int, BigInteger>()
1823

19-
/**
20-
* worst time: O(n)
21-
* the best time: O(1)
22-
* amount of memory: O(n)
23-
* problem: creating a huge number of BigInteger objects
24-
*/
2524
fun compute(number: Int) : BigInteger {
2625
if (number <= 1) {
2726
return BigInteger.ONE

‎src/main/kotlin/other/FactorialWithCache.kt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,16 @@ package other
66
*
77
* optimization: caching previous factorial values
88
*
9+
* worst time: O(n)
10+
* the best time: O(1)
11+
* amount of memory: O(n)
12+
*
913
*/
1014

1115
class FactorialWithCache {
1216

1317
private val cache = hashMapOf<Int, Int>()
1418

15-
/**
16-
* worst time: O(n)
17-
* the best time: O(1)
18-
* amount of memory: O(n)
19-
*/
2019
fun compute(number: Int) : Int {
2120
if (number <= 1) {
2221
return 1

‎src/main/kotlin/other/KnuthMorrisPratt.kt

Lines changed: 0 additions & 45 deletions
This file was deleted.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package other
2+
3+
/**
4+
*
5+
* Knut Morris Pratt's Algorithm for finding a substring in a string
6+
*
7+
*/
8+
9+
class KnuthMorrisPrattAlgorithm {
10+
11+
// returns true if the substring is in the string
12+
fun contains(sub: String, str: String) : Boolean {
13+
val summary = "$sub$SEPARATOR$str"
14+
val prefixFunctionValue = prefixFunction(summary)
15+
return prefixFunctionValue.any { value -> value == sub.length }
16+
}
17+
18+
// returns the number of occurrences of a substring in a string
19+
fun count(sub: String, str: String) : Int {
20+
val summary = "$sub$SEPARATOR$str"
21+
return prefixFunction(summary).count { value -> value == sub.length }
22+
}
23+
24+
// returns an array of prefix functions for a string
25+
private fun prefixFunction(str: String) : Array<Int> {
26+
val prefixFunctionsValues = Array(str.length) { 0 }
27+
for (index in 1 until str.length) {
28+
var prefixFunctionValue = prefixFunctionsValues[index - 1]
29+
while (prefixFunctionValue > 0 && str[index] != str[prefixFunctionValue]) {
30+
prefixFunctionValue = prefixFunctionsValues[prefixFunctionValue - 1]
31+
}
32+
if (str[index] == str[prefixFunctionValue]) {
33+
prefixFunctionValue++
34+
}
35+
prefixFunctionsValues[index] = prefixFunctionValue
36+
}
37+
return prefixFunctionsValues
38+
}
39+
40+
companion object {
41+
// delimiter must not occur in source strings
42+
private const val SEPARATOR = "#"
43+
}
44+
45+
}

‎src/main/kotlin/other/LevensteinLength.kt renamed to ‎src/main/kotlin/other/LevenshteinLengthAlgorithm.kt

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,8 @@ import java.lang.Integer.min
88
*
99
*/
1010

11-
class LevenshteinLength {
11+
class LevenshteinLengthAlgorithm {
1212

13-
/**
14-
* determines the Levenshtein distance for two strings and returns it
15-
*/
1613
fun compute(str1: String, str2: String) : Int {
1714
val matrix = Array(str1.length + 1) {
1815
Array(str2.length + 1) { 0 }

‎src/main/kotlin/other/Max.kt renamed to ‎src/main/kotlin/other/MaxAlgorithm.kt

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,11 @@ import java.lang.IllegalArgumentException
88
*
99
*/
1010

11-
class Max<T:Comparable<T>> {
11+
class MaxAlgorithm {
1212

13-
/**
14-
* returns the maximum element from the list
15-
*/
16-
fun compute(items: List<T>) : T {
13+
fun <T : Comparable<T>> compute(items: List<T>) : T {
1714
if (items.isEmpty()) {
18-
throw IllegalArgumentException("items is empty!")
15+
throw IllegalArgumentException("items list is empty!")
1916
}
2017
var max = items[0]
2118
for (i in 1 until items.size) {
@@ -29,7 +26,10 @@ class Max<T : Comparable<T>> {
2926
/**
3027
* returns the maximum element from the list recursively
3128
*/
32-
fun computeRecursive(items: List<T>) : T {
29+
fun <T : Comparable<T>> computeRecursive(items: List<T>) : T {
30+
if (items.isEmpty()) {
31+
throw IllegalArgumentException("items list is empty!")
32+
}
3333
if (items.size == 1) {
3434
return items.first()
3535
}

‎src/main/kotlin/other/Min.kt renamed to ‎src/main/kotlin/other/MinAlgorithm.kt

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,11 @@ import java.lang.IllegalArgumentException
88
*
99
*/
1010

11-
class Min<T:Comparable<T>> {
11+
class MinAlgorithm {
1212

13-
/**
14-
* returns the minimum element from the list
15-
*/
16-
fun compute(items: List<T>) : T {
13+
fun <T : Comparable<T>> compute(items: List<T>) : T {
1714
if (items.isEmpty()) {
18-
throw IllegalArgumentException("items is empty!")
15+
throw IllegalArgumentException("items list is empty!")
1916
}
2017
var min = items[0]
2118
for (i in 1 until items.size) {
@@ -26,10 +23,10 @@ class Min<T : Comparable<T>> {
2623
return min
2724
}
2825

29-
/**
30-
* returns the minimum element from the list recursively
31-
*/
32-
funcomputeRecursive(items:List<T>) : T {
26+
fun <T:Comparable<T>> computeRecursive(items:List<T>) : T {
27+
if (items.isEmpty()) {
28+
throwIllegalArgumentException("items list is empty!")
29+
}
3330
if (items.size == 1) {
3431
return items.first()
3532
}

‎src/main/kotlin/search/BinarySearch.kt

Lines changed: 48 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,56 @@ package search
22

33
/**
44
*
5-
* name: binary search algorithm
5+
* Binary search algorithm only works for sorted lists and arrays
66
*
7-
* description: one of the most important features of this algorithm
8-
* is that it only works for sorted lists and arrays
9-
*
10-
* time: log(n)
7+
* best time: 1
8+
* worst time: log(n)
119
* amount of memory: 1
1210
*
1311
*/
1412

15-
class BinarySearch<T : Comparable<T>> {
13+
class BinarySearch {
14+
15+
// searches for an element in the array and returns the index of the searched element or -1
16+
fun <T : Comparable<T>> search(array: Array<T>, element: T) : Int {
17+
if (array.isEmpty()) return -1
18+
19+
var left = 0
20+
var right = array.size
21+
while (left < right) {
22+
val middle = left + (right - left) / 2
23+
if (array[middle] < element) {
24+
left = middle + 1
25+
} else if (array[middle] > element) {
26+
right = middle
27+
} else {
28+
return middle
29+
}
30+
}
31+
return -1
32+
}
33+
34+
// recursive method
35+
// P.S. The tailrec modifier tells the compiler to optimize the recursion and turn it into an iterative version
36+
tailrec fun <T : Comparable<T>> searchRecursive(array: Array<T>, element: T, left: Int = 0, right: Int = array.size - 1): Int {
37+
if (left <= right) {
38+
val middle = left + (right - left) / 2
39+
if (array[middle] == element) {
40+
return middle
41+
}
42+
return if (array[middle] > element) {
43+
searchRecursive(array, element, left, middle - 1)
44+
} else {
45+
searchRecursive(array, element, middle + 1, right)
46+
}
47+
}
48+
return -1
49+
}
50+
51+
// finds the left border index to insert an element into a sorted array
52+
fun <T : Comparable<T>> leftBound(array: Array<T>, element: T) : Int {
53+
if (array.isEmpty()) return 0
1654

17-
/**
18-
* finds the left border index to insert an element [element] into a sorted array [array]
19-
*/
20-
fun leftBound(array: Array<T>, element: T) : Int {
2155
var left = -1
2256
var right = array.size
2357
while ((right - left) > 1) {
@@ -31,10 +65,10 @@ class BinarySearch<T : Comparable<T>> {
3165
return left
3266
}
3367

34-
/**
35-
* finds the right border index to insert an element [element] into a sorted array [array]
36-
*/
37-
funrightBound(array:Array<T>, element:T) : Int {
68+
// finds the right border index to insert an element into a sorted array
69+
fun <T:Comparable<T>> rightBound(array:Array<T>, element:T) : Int {
70+
if (array.isEmpty()) return-1
71+
3872
var left = -1
3973
var right = array.size
4074
while ((right - left) > 1) {
@@ -48,30 +82,4 @@ class BinarySearch<T : Comparable<T>> {
4882
return right
4983
}
5084

51-
/**
52-
* checks if an element [element] is in an array [array] and returns true if the element is present in the array, false otherwise
53-
*/
54-
fun exists(array: Array<T>, element: T): Boolean {
55-
return search(array, element) != -1
56-
}
57-
58-
/**
59-
* searches for an element [element] in an array [array] and returns the index of the searched element or -1
60-
*/
61-
fun search(array: Array<T>, element: T) : Int {
62-
var left = 0
63-
var right = array.size - 1
64-
while (left <= right) {
65-
val middle = (left + right) / 2
66-
if (array[middle] < element) {
67-
left = middle + 1
68-
} else if (array[middle] > element) {
69-
right = middle
70-
} else {
71-
return middle
72-
}
73-
}
74-
return -1
75-
}
76-
7785
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /