Skip to content

Instantly share code, notes, and snippets.

@ericntd
Last active December 15, 2020 18:31
Show Gist options
  • Save ericntd/bc806efffe4520bd88104da72fa11cab to your computer and use it in GitHub Desktop.
Save ericntd/bc806efffe4520bd88104da72fa11cab to your computer and use it in GitHub Desktop.
Find matching records in 2 text files with Binary Search Tree
package matching_logs
import java.io.File
data class BinarySearchTree(
private val data: String,
internal var left: BinarySearchTree? = null,
internal var right: BinarySearchTree? = null
) {
private fun compare(s1: String, s2: String): Int {
val name1 = s1.extractJustClassName()
val name2 = s2.extractJustClassName()
return name1.compareTo(name2)
}
fun insert(newData: String) {
val insertData = newData.removeEndingColon()
if (compare(insertData, this.data) >= 0) {
if (right != null) {
right!!.insert(insertData)
} else {
val leaf = BinarySearchTree(insertData)
this.right = leaf
}
} else {
if (left != null) {
left!!.insert(insertData)
} else {
val leaf = BinarySearchTree(insertData)
this.left = leaf
}
}
}
fun search(theData: String): Boolean {
val searchData = theData.removeEndingColon()
if (searchData == this.data) return true
return if (compare(searchData, this.data) > 0) {
if (right != null) {
right!!.search(searchData)
} else {
false
}
} else {
if (left != null) {
left!!.search(searchData)
} else {
false
}
}
}
}
private fun String.extractJustClassName() = substring(this.lastIndexOf("."))
private fun String.removeEndingColon(): String {
return if (this.endsWith(":")) {
this.substring(0, this.length - 1)
} else {
this
}
}
fun main() {
val mappingReader = File("/Users/ericn/tmp/algo/kotlin/src/matching_logs/mapping.txt").bufferedReader()
val mappingTree = BinarySearchTree("com.myawesomeapp.ghafaewafe") // hopefully the tree will be balance
mappingReader.lines().forEach {
if (it.startsWith("com.myawesomeapp") && !it.contains("$") && !it.contains("_")) {
val arrowIndex = it.indexOf("->")
mappingTree.insert(it.substring(0, arrowIndex - 1))
}
}
val usageReader = File("/Users/ericn/tmp/algo/kotlin/src/matching_logs/usage.txt").bufferedReader()
val unusedClasses = mutableListOf<String>()
val usedClasses = mutableListOf<String>()
usageReader.lines().forEach {
if (it.startsWith("com.myawesomeapp") && !it.contains("$") && !it.contains("_") && !it.endsWith(".R") && !it.endsWith(".R:") && !it.endsWith("Binding") && !it.endsWith("BuildConfig") && !it.contains("Test")) {
if (mappingTree.search(it)) {
usedClasses.add(it)
} else {
unusedClasses.add(it)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment