DEV Community

Discussion on: How to Solve Sock Merchant Code Challenge

Collapse
 
johnmilimo profile image
JMW

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

Collapse
 
nomadkitty profile image
Jojo Zhang

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