Created
May 22, 2013 15:56
-
-
Save tyrcho/5628694 to your computer and use it in GitHub Desktop.
Analyse the frequency of repeated chars in a given string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.Random | |
import scala.collection.immutable.SortedMap | |
object ATGC extends App { | |
def randomString(size: Int) = List.fill(size)(randomChar).mkString | |
def randomChar = "ATGC"(Random.nextInt(4)) | |
def analyze(s: String): Map[String, Int] = { | |
val (_, _, res) = (s + "Z").tail.foldLeft((s.head, 1, SortedMap.empty[String, Int] withDefaultValue 0)) { | |
case ((last, count, map), current) if current == last => (last, count + 1, map) | |
case ((last, count, map), current) if current != last => | |
val key = last.toString * count | |
val value = map(key) + 1 | |
(current, 1, map.updated(key, value)) | |
} | |
res | |
} | |
val s = randomString(10) | |
println(s) | |
println(analyze(s)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment