Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,086 questions

55,960 answers

573 users

How to find the frequency of each digit (0–9) in a number with Scala

1 Answer

0 votes
object DigitCounter {

  /**
    * Counts how many times each digit (0–9) appears in a given number.
    *
    * @param number The input number (Long or Int)
    * @return A Map[Int, Int] where key = digit, value = frequency
    */
  def digitFrequency(number: Long): Map[Int, Int] = {

    // Convert number to string so we can iterate over each character
    val digits = number.toString

    // Initialize a map with digits 0–9 all starting at frequency 0
    val initialFreq = (0 to 9).map(d => d -> 0).toMap

    // Fold over the digits, updating the frequency map
    digits.foldLeft(initialFreq) { (freqMap, ch) =>
      val digit = ch.asDigit
      freqMap.updated(digit, freqMap(digit) + 1)
    }
  }

  def main(args: Array[String]): Unit = {
    val number = 120220340501L

    // Call the function
    val freq = digitFrequency(number)

    // Print the result (this line is valid)
    println(freq)
  }
}



/*
run:

HashMap(0 -> 4, 5 -> 1, 1 -> 2, 6 -> 0, 9 -> 0, 2 -> 3, 7 -> 0, 3 -> 1, 8 -> 0, 4 -> 1)

*/

 



answered Jul 2 by avibootz
...