0

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.

John Doe
  • 79
  • 1
  • 4

3 Answers3

3

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}
RobCo
  • 6,240
  • 2
  • 19
  • 26
3

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.

Arpit Shukla
  • 9,612
  • 1
  • 14
  • 40
0

Firstly check n number is contain this map as key, if found then increment 1 its value using plus method. If not found any value from the map, it will null and check if null and set 1.

       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)
Poran
  • 532
  • 4
  • 9