therealbluepandabear
03/10/2021, 2:06 AMYoussef Shoaib [MOD]
03/10/2021, 2:22 AMconst 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.Matteo Mirk
03/10/2021, 7:23 AMfun 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
w.toCharArray()
.filter { normalizeCase(it) in 'A'..'Z' } // 'it' is the implicit lambda argument; '..' constructs a range
.distinct()
.size
}
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")
println(mostUniqueLetters(words))
}
🆒 solution @Youssef Shoaib [MOD]!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' }