Can `maxDigits` function be simplified? I want to ...
# announcements
i
Can
maxDigits
function be simplified? I want to find what is the longest digit in the list and return length of that digit. Method works but can it be done using kotlin stdlib functions without using digit length (
digitCount
) twice ?
Copy code
val Int.digitCount get() = this.toString().length

fun maxDigits(list: List<Int>): Int = list.maxBy { it.digitCount }?.digitCount ?: 0
d
Uhh,
list.max() ?: 0
?
Misread question.
s
Looking at the digitCount property alone: You might want to use log10 instead of stringification for performance reasons. List -> Sequence -> map digitCount -> max() might do what you want
1
👍 1
@Dominaezzz ignoring negative numbers, you are correct, aren't you?
d
Yes, although the question is only about avoiding the second call to
digitCount
.
🆗 1
k
There isn't any way to do this AFAIK, either do this or
map { }.max()
i
This is god enough for me 🙂 Also
max
may return null so at the end we need something like this:
Copy code
fun maxDigits(list: List<Int>) = list.map { it.digitCount }.max() ?: 0
Additionaly we could boost performance by using sequence and
log10
(as @SiebelsTim mentioned):
Copy code
private val Int.digitCount: Int
        get() = when (this) {
            0 -> 1
            else -> Math.log10(Math.abs(this.toDouble())).toInt() + 1
        }
k
Be careful, sequences don't necessarily improve performance. If you're going to write a util function
maxDigits
you might as well do the fastest thing possible and write out the for loop.
d
Might as well change
0 -> 1
to
0..9 -> 1
🧌
k
-9..9
d
I wonder if it would be faster to manually type out all 10 cases. 🤔
And if Kotlin will let you omit the
else
.
k
It won't, there's basically no support for smart `when`s.
Stuff like this really bothers me:
Copy code
val f = when {
    x > 0 -> ...
    x == 0 -> ...
    x < 0 -> ...
    //error: expected else
}
😮 1
d
I usually leave out the
x == 0
for the
else
but explicitness can be nice sometimes.
k
But
0
is between
> 0
and
< 0
. There are no winners here.
d
😞
k
I thought there was an issue for this but now I can't find it, this is related though: https://youtrack.jetbrains.com/issue/KT-20943,