# getting-started


03/10/2021, 2:06 AM
Hi... I've been trying to find a solution to this - I was wondering if someone could work with me regarding this; rather new to Kotlin. I'm analysing a lot of words. I am trying to find the word which contains the most unique letters from (A-Z) and return it. Does anyone know a way to do this in Kotlin? I've been trying to for quite some time. Haven't seemed to find a way yet. Tom

Youssef Shoaib [MOD]

03/10/2021, 2:22 AM
Here you go (playground):
Copy code
const val allowLowercase = false //change to true to make the code output "abcdefgh" instead
fun main(){
    val inputStrings = listOf("ABC", "A B /c", "A  B", "ABCDEFG", "£%$^$%^$%&$", "abcdefgh")
    println(inputStrings.maxByOrNull{ it.toCharArray().filter {(if(allowLowercase) it.toUpperCase() else it) in 'A'..'Z' }.distinct().size})
In a nutshell, this code finds the string in inputStrings that produces the highest number from the lambda that we're passing in to maxByOrNull. That number is basically every single letter in that string that is from A-Z (or a-z and A-Z if you enable allowLowercase). We calculate that number by first converting the string to CharArray (because it has more collection-y operations than String) and then we filter out all the characters that shouldn't count, then we filter out any duplicates by calling distinct and finally we get the number of the remaining, valid characters and use that as our "maxing" determiner.
👍 1

Matteo Mirk

03/10/2021, 7:23 AM
Since Tom is a beginner with Kotlin, maybe formatting the code less densely could help him reading
Copy code
fun mostUniqueLetters(words: List<String>) = // expression body: avoids {}, 'return' and explicit return type
    words.maxByOrNull { w -> // explicit lambda argument to avoid shadowing the inner implicit argument
            .filter { normalizeCase(it) in 'A'..'Z' } // 'it' is the implicit lambda argument; '..' constructs a range

const val allowLowercase = false //change to true to make the code output "abcdefgh" instead

fun normalizeCase(it: Char) = if (allowLowercase) it.toUpperCase() else it // extracted for better readability

fun main() {
    val words = listOf("ABC", "A B /c", "A  B", "ABCDEFG", "£%$^$%^$%&$", "abcdefgh")
🆒 solution @Youssef Shoaib [MOD]!
👍 2
@therealbluepandabear I realized that here we could use an extension function for better readability, depending on individual taste:
Copy code
fun Char.normalizeCase() = if (allowLowercase) this.toUpperCase() else this // notice 'this' replaces the 'it' argument

// then its usage becomes:
.filter { it.normalizeCase() in 'A'..'Z' }