https://kotlinlang.org logo
#getting-started
Title
# getting-started
д

Дмитрий Цывцын

02/03/2022, 2:30 AM
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

Alex

02/03/2022, 1:05 PM
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
д

Дмитрий Цывцын

02/04/2022, 6:08 AM
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

Alex

02/07/2022, 7:59 AM
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()
    }
д

Дмитрий Цывцын

02/10/2022, 3:32 AM
My solutions are fully working. Use them :)
a

Alex

02/10/2022, 12:09 PM
Hi @*Дмитрий Цывцын*, Yes they all work, thank you so much!!😄
2 Views