If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, July 24, 2013

Finding second highest frequency of characters in String

Write a method that accepts a String and returns the character with the second highest frequency. For example "aabbbc" would return 'a'. If the string contains spaces, they can be disregarded from the count. Note: my implementation returns a tuple (char, count) but that is just a matter of only returning the char itself.
package puzzlers
import scala.collection.mutable.{Map => MMap}
object HighestFrequencyPuzzle {
def stringToCharFrequencyMap(source: String): MMap[Char, Int] = {
source.filter(c => c!=' ').foldLeft(MMap[Char, Int]())((map, char) => {
map.update(char, map.getOrElseUpdate(char, 0) + 1)
map
})
}
def getNthHighestFrequency(source: String, n: Int): (Char, Int) =
stringToCharFrequencyMap(source).toList.sortBy(_._2).reverse.drop(n -1).take(1)(0)
def main(args: Array[String]): Unit = {
val highest = getNthHighestFrequency("abecbb cdcbef", 1)
println(highest)
val secondHighest = getNthHighestFrequency("abecbb cdcbef", 2)
println(secondHighest)
}
}
/** output
(b,4)
(c,3)
**/
view raw gistfile1.scala hosted with ❤ by GitHub

1 comment: