Hello. If you are starting to learn algorithms, us...
# getting-started
д
Hello. If you are starting to learn algorithms, use my repository with the simplest and most famous algorithms on Kotlin!!!! Algorithms on Kotlin
🙌🏻 1
🙌 1
a
Hi @Дмитрий Цывцын Based on your repository ,kindly advise me,which algorithm suits to solve the below Code wars problem. https://kotlinlang.slack.com/archives/C0B8MA7FA/p1643814761785979
д
Hi! Have you already solved the problem?
Copy code
// Solution #1
fun deleteNth1(elements: IntArray, maxOccurrences: Int) : IntArray {
    //  LinkedHashMap preserves the entry iteration order.
    val occurrencesMap = LinkedHashMap<Int, Int>()
    elements.forEach { element ->
        occurrencesMap[element] = (occurrencesMap[element] ?: 0) + 1
    }
    return occurrencesMap.map { entry ->
        val occurrences = if (entry.value < maxOccurrences) entry.value else maxOccurrences
        Array(occurrences) { entry.key }
    }.toTypedArray().flatten().toIntArray()
}

// Solution #2
fun deleteNth2(elements: IntArray, maxOccurrences: Int) : IntArray {
    return elements.groupBy { it }
        .flatMap { group -> group.value.take(maxOccurrences) }
        .toIntArray()
}

// Solution #3
fun deleteNth3(elements: IntArray, maxOccurrences: Int) : IntArray {
    val occurrencesMap = LinkedHashMap<Int, Int>()

    // array can be larger
    val array = Array(elements.size) { 0 }

    var index = 0
    for (element in elements) {
        val occurrences = occurrencesMap[element] ?: 0
        val newOccurrences = occurrences + 1

        if (newOccurrences <= maxOccurrences) {
            array[index] = element
        }

        occurrencesMap[element] = newOccurrences
    }
    
    return array.toIntArray()
}
💯 1
a
Hi @Дмитрий Цывцын, sorry for late reply this is what i came up with on my own
Copy code
//This code works but it changes the order thus code wars does not acccept it
    fun getMaxOccurrence2(elements:IntArray, maxOccurrences:Int):IntArray{
        var holdResult= listOf<Int>()
        val result=elements.asSequence().groupBy { it }.values
        for (items in result){
            if (items.count()< maxOccurance){
                continue
            }
            holdResult=holdResult.plus(items.take(maxOccurrences))
        }
        return holdResult.toIntArray()
    }
д
My solutions are fully working. Use them :)
a
Hi @*Дмитрий Цывцын*, Yes they all work, thank you so much!!😄