Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active February 19, 2025 21:23
Show Gist options
  • Save rshepherd/d1e5ad973278e642bcd2c9a20f98f763 to your computer and use it in GitHub Desktop.
Save rshepherd/d1e5ad973278e642bcd2c9a20f98f763 to your computer and use it in GitHub Desktop.
A small portion of a toy SkipList with polymorphic find for instructional purposes
class SkipList {
data class Node<Value>(val id: Value, val children: MutableList<Node<Value>> = mutableListOf())
abstract class Value<T>(val value: T) {
abstract fun distance(other: T): Int
}
class IntValue(id: Int) : Value<Int>(id) {
override fun distance(other: Int): Int = kotlin.math.abs(this.value - other)
}
fun <V : Value<T>, T> find(findMe: V, node: Node<V>): Node<V>? {
// If this node is the one we are looking for, return it
if (findMe.value == node.id.value) return node
// If this node has no children, value is not present
if (node.children.isEmpty()) return null
// Traverse the children to see if the target is present
node.children.forEach {
if (it.id.value == findMe.value) return it
}
// Find the best child to traverse based on distance
val bestChild = node.children.minByOrNull { child ->
findMe.distance(child.id.value)
} ?: return null
// Recursively call `find` on the best child
return find(findMe, bestChild)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment