All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.net.ormr.fuzzywuzzy.algorithms.utils.kt Maven / Gradle / Ivy

package net.ormr.fuzzywuzzy.algorithms

import net.ormr.fuzzywuzzy.internal.PriorityQueue

private val TOKENIZE_REGEX = """\s+""".toRegex()

internal inline fun  buildMutableList(builder: MutableList.() -> Unit): MutableList =
    mutableListOf().apply(builder)

internal fun String.tokenize(): List = split(TOKENIZE_REGEX).dropLastWhile { it.isEmpty() }

internal fun String.tokenizeSet(): Set = tokenize().toHashSet()

internal fun MutableList.sortAndJoin(separator: String): String {
    sort()
    return join(separator)
}

internal fun List.join(separator: String): String = buildString(size * 16) {
    for (i in [email protected]) {
        if (i < size) {
            append(separator)
        }

        append(this@join[i])
    }
}.trim { it <= ' ' }

internal fun Set.sortAndJoin(separator: String): String = toMutableList().sortAndJoin(separator)

internal fun > List.findTopKHeap(k: Int): MutableList {
    val queue = PriorityQueue()

    for (x in this) {
        when {
            queue.size < k -> queue.add(x)
            x > queue.peek()!! -> {
                queue.poll()
                queue.add(x)
            }
        }
    }

    return buildMutableList {
        for (i in k downTo 1) {
            val polled = queue.poll()

            if (polled != null) {
                add(polled)
            }
        }
    }
}

internal fun > Sequence.findTopKHeap(k: Int): Sequence {
    val queue = PriorityQueue()

    for (x in this) {
        when {
            queue.size < k -> queue.add(x)
            x > queue.peek()!! -> {
                queue.poll()
                queue.add(x)
            }
        }
    }

    return sequence {
        for (i in k downTo 1) {
            val polled = queue.poll()

            if (polled != null) {
                yield(polled)
            }
        }
    }
}

internal fun > max(vararg elements: T): T? {
    if (elements.isEmpty()) return null

    var best = elements[0]

    for (t in elements) {
        if (t > best) {
            best = t
        }
    }

    return best
}

internal fun max(vararg elements: Double): Double {
    if (elements.isEmpty()) return 0.0

    var best = elements[0]

    for (t in elements) {
        if (t > best) {
            best = t
        }
    }

    return best
}

internal fun max(vararg elements: Int): Int {
    if (elements.isEmpty()) return 0

    var best = elements[0]

    for (t in elements) {
        if (t > best) {
            best = t
        }
    }

    return best
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy