How to find the second most frequent character in a string with Scala

2 Answers

0 votes
object SecondMostFrequentChar_Scala {
  def main(args: Array[String]): Unit = {
    val str = "bbaddddccce"
    
    // Step 1: Generate frequency map
    val frequencyMap = str.groupBy(identity).mapValues(_.length)
    
    // Step 2: Sort the map by frequency in descending order
    val sortedByFrequency = frequencyMap.toSeq.sortWith(_._2 > _._2)
    
    // Step 3: Extract the second most frequent character
    if (sortedByFrequency.length > 1) {
      val secondMostFrequent = sortedByFrequency(1)._1
      println(s"The second most frequent character is: '$secondMostFrequent'")
    } else {
      println("The string does not have enough unique characters.")
    }
  }
}
 
 
 
/*
run:
   
The second most frequent character is: 'c'
 
*/

 



answered Nov 29, 2024 by avibootz
0 votes
object SecondMostFrequentChar_Scala {
  def main(args: Array[String]): Unit = {
    val str = "bbaddddccce"

    // Initialize variables to track top two frequencies and characters
    var firstMaxFreq = 0
    var firstMaxChar = ' '
    var secondMaxFreq = 0
    var secondMaxChar = ' '

    // Iterate through the string and update the frequencies
    str.foreach { c =>
      val freq = str.count(_ == c)
      if (freq > firstMaxFreq) {
        secondMaxFreq = firstMaxFreq
        secondMaxChar = firstMaxChar
        firstMaxFreq = freq
        firstMaxChar = c
      } else if (freq > secondMaxFreq && freq != firstMaxFreq) {
        secondMaxFreq = freq
        secondMaxChar = c
      }
    }

    if (secondMaxFreq > 0) {
      println(s"The second most frequent character is: '$secondMaxChar'")
    } else {
      println("The string does not have enough unique characters.")
    }
  }
}
 
 
 
/*
run:
   
The second most frequent character is: 'c'
 
*/

 



answered Nov 29, 2024 by avibootz
...