Home > Software engineering >  Having an issue with mutablemap in Kotlin
Having an issue with mutablemap in Kotlin

Time:11-25

I'm working on an algorithm type challenge, and i am debugging via print statements and i can't seem to figure out why the the values for keys are not what i am expecting

 var mapNums = mutableMapOf<Int, Int>()

//imaginary array
    //var nums = [34,28,11,21,3,34,8,7,34,7,31,7,3,28,18]
    var count = 0
    

    for (n in nums) {

        if (mapNums.containsKey(n)) {
            count   
            mapNums[n] = count
        } else if (!mapNums.containsKey(n)) {
            count = 1
            mapNums[n] = count
        }

    }

    println(mapNums)

//prints {34=2, 28=4, 11=1, 21=1, 3=3, 8=1, 7=2, 31=1, 18=1}

as you can see the key and values aren't what theyre supposed to be and i am not sure why.

CodePudding user response:

It's because you reuse the same count variable outside of the loop so it keeps incrementing from different keys.

Instead you should get the current count from the map, then put it back one higher:

val nums = intArrayOf(34,28,11,21,3,34,8,7,34,7,31,7,3,28,18)
val mapNums = mutableMapOf<Int, Int>()

for (n in nums) {
    val count = mapNums[n] ?: 0
    mapNums[n] = count   1
}

println(mapNums) // {34=3, 28=2, 11=1, 21=1, 3=2, 8=1, 7=3, 31=1, 18=1}

CodePudding user response:

You can use the following code to generate the desired map:

val nums = intArrayOf(34, 28, 11, 21, 3, 34, 8, 7, 34, 7, 31, 7, 3, 28, 18).toList()
println(nums.groupingBy { it }.eachCount())

try it yourself

Here groupingBy creates a Grouping source using the same element as the key selector. Then eachCount groups elements from the Grouping source by key and counts elements in each group.

You can also refer the documentation for more info about groupingBy and eachCount.

CodePudding user response:

 var mapNums = mutableMapOf<Int, Int>()
    //imaginary array
        var nums = arrayOf(34,28,11,21,3,34,8,7,34,7,31,7,3,28,18)
        
        for (n in nums) {
    
        mapNums[n] = mapNums[n]?.plus(1) ?: 1
    
        }
    
        println(mapNums)
  • Related