I need to write a function that returns a List
of (Char, Int)
pairs given an input String
.
My solution produces the correct result but I'm wondering if there is a better way:
def countChars(s: String): List[(Char, Int)] = {
s.groupBy(c => c.toLower).flatMap(e => List((e._1, e._2.length))).toList
}
This produces a result like this in a worksheet:
countChars("Green Grass")
// res0: List[(Char, Int)] = List(('e', 2), ('s', 2), ('n', 1), ('a', 1), (' ', 1), ('g', 2), ('r', 2))
To count the number of unique characters in a string:Use the set() class to convert the string to a set of unique characters. Use the len() function to get the number of unique characters in the string.
A unique string consists of characters that occur only once. To check for uniqueness, compare each character with the rest of the string. If a character is repeated, then the string is not unique.
Making a singleton List just to flatten it is redundant.
"Green Grass".groupBy(c => c.toLower).map(e => (e._1, e._2.length)).toList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With