Skip to content

Instantly share code, notes, and snippets.

@samidarko
Last active August 14, 2016 08:31
Show Gist options
  • Save samidarko/8728b8b6450c05a30b908568e535e016 to your computer and use it in GitHub Desktop.
Save samidarko/8728b8b6450c05a30b908568e535e016 to your computer and use it in GitHub Desktop.
Count the number of occurrences in a string over consumption
def countOccurrences (s: String): String = s span (x => x == s.head) match {
case ("", "") => ""
case (fw, rest) => fw.length.toString + fw.head ++ countOccurrences(rest)
}
countOccurrences("") // ""
countOccurrences("aaa") // "3a"
countOccurrences("aaabbb") // "3a3b"
countOccurrences("aaabbbccchhhhhhddddhhhheee") // "3a3b3c6h4d4h3e"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment