loading...

re: How to Solve Sock Merchant Code Challenge VIEW POST

FULL DISCUSSION
 

Solution in kotlin:

fun main() {
    val colors = arrayOf(10, 20, 20, 10, 10, 30, 50, 10, 20)
    var pairs = 0
    val colorFrequencies: MutableMap<Int, Int> = mutableMapOf()
    colors.forEach { color ->
        val count = colorFrequencies.getOrDefault(color, 0)
        colorFrequencies[color] = count+1
    }
    colorFrequencies.forEach { entry ->
        pairs += entry.value / 2
    }
    println(pairs)
}

Basically you store the frequency of each colour in a map, then you perform division by 2 on each entry value

 

Very interesting. I can see some syntax similarities between JavaScript and Kotlin. Thanks for sharing.

Code of Conduct Report abuse