igor.wojda
02/23/2019, 4:45 PMmaxDigits 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 ?
val Int.digitCount get() = this.toString().length
fun maxDigits(list: List<Int>): Int = list.maxBy { it.digitCount }?.digitCount ?: 0Dominaezzz
02/23/2019, 4:47 PMlist.max() ?: 0?SiebelsTim
02/23/2019, 4:48 PMSiebelsTim
02/23/2019, 4:51 PMDominaezzz
02/23/2019, 4:53 PMdigitCount.karelpeeters
02/23/2019, 5:28 PMmap { }.max()igor.wojda
02/23/2019, 5:53 PMmax may return null so at the end we need something like this:
fun maxDigits(list: List<Int>) = list.map { it.digitCount }.max() ?: 0
Additionaly we could boost performance by using sequence and log10 (as @SiebelsTim mentioned):
private val Int.digitCount: Int
get() = when (this) {
0 -> 1
else -> Math.log10(Math.abs(this.toDouble())).toInt() + 1
}karelpeeters
02/23/2019, 5:55 PMmaxDigits you might as well do the fastest thing possible and write out the for loop.Dominaezzz
02/23/2019, 5:57 PM0 -> 1 to 0..9 -> 1 🧌karelpeeters
02/23/2019, 5:57 PM-9..9Dominaezzz
02/23/2019, 6:01 PMDominaezzz
02/23/2019, 6:02 PMelse.karelpeeters
02/23/2019, 6:02 PMkarelpeeters
02/23/2019, 6:03 PMval f = when {
x > 0 -> ...
x == 0 -> ...
x < 0 -> ...
//error: expected else
}Dominaezzz
02/23/2019, 6:04 PMx == 0 for the else but explicitness can be nice sometimes.karelpeeters
02/23/2019, 6:05 PM0 is between > 0 and < 0. There are no winners here.Dominaezzz
02/23/2019, 6:08 PMkarelpeeters
02/23/2019, 6:09 PM