Find similarities between two strings in Kotlin
This article explores different ways to find similarities between two strings in Kotlin using the Levenshtein distance algorithm.
The Levenshtein distance (aka Edit distance) is used to find how different two sequences are from one another. It works by counting the minimum number of operations required to transform one sequence to another.
The following example uses Levenshtein distance to determine the string similarity in between 0 and 1 (both inclusive). We can easily modify the code to ignore the case or output the similarity in percentage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import kotlin.math.max import kotlin.math.min fun getLevenshteinDistance(X: String, Y: String): Int { val m = X.length val n = Y.length val T = Array(m + 1) { IntArray(n + 1) } for (i in 1..m) { T[i][0] = i } for (j in 1..n) { T[0][j] = j } var cost: Int for (i in 1..m) { for (j in 1..n) { cost = if (X[i - 1] == Y[j - 1]) 0 else 1 T[i][j] = min(min(T[i - 1][j] + 1, T[i][j - 1] + 1), T[i - 1][j - 1] + cost) } } return T[m][n] } fun findSimilarity(x: String?, y: String?): Double { require(!(x == null || y == null)) { "Strings should not be null" } val maxLength = max(x.length, y.length) return if (maxLength > 0) { (maxLength * 1.0 - getLevenshteinDistance(x, y)) / maxLength * 1.0 } else 1.0 } fun main() { val similarity = findSimilarity("ABABABABCCCCABABABC", "ABABABABCCCCABABR") println(similarity) // 0.8421052631578947 } |
That’s all about finding similarities between two strings in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)