Problem with finding the longest word in map

100 Views Asked by At

I have such a code, in general it works correctly, but if there is a maximum long word and it is followed by the same words in length, then it will return only 1 long word, and I need to get the last long word. Here's what I mean, such input: AWord BWord ALongWord BLongWord CLongWord. My code will output an (A)ALongWord but should output a (C)CLongWord because it is the most recent.

fun main(){
    val result1 = readLine()?.split(" ")?.associateWith { it.length }?.maxBy { it.value }.let{it?.key?.get(0)}.let { println(it) }
}

I assume that this can be done with reduce, but I don't quite understand how, probably my implementation needs to be redone because maxBy does not allow it to be done, if possible, fix my code or offer your solution. This is a learning task and it involves using functions over collections.

1

There are 1 best solutions below

0
On

maxBy finds the first occurrence of the maximum element, not the last.

If you want the last maximum element, you can simply do maxBy after reversing (asReversed) the list of strings you got from split.

Consider using maxByOrNull instead of maxBy so that you get a null instead of an exception when the user entered nothing.

Also, I'm not sure why you made a map out of this. That is unnecessary. You also shouldn't assign the result of let { println(...) } to a val. That is the Unit object, not the result you want.

If you want to store the result somewhere and also print it, use also:

val result = readlnOrNull()
    ?.split(" ")
    ?.asReversed()
    ?.maxByOrNull { it.length }
    ?.also { println(it) }