Skip to content

Instantly share code, notes, and snippets.

@DarkDesire
Created November 15, 2016 08:00
Show Gist options
  • Save DarkDesire/906c2860be38f58672048c0267edec74 to your computer and use it in GitHub Desktop.
Save DarkDesire/906c2860be38f58672048c0267edec74 to your computer and use it in GitHub Desktop.
Частота символа в списке символов
val str = "abAsdhqfdkjggjsjfpg".toList
val str1 = str
.groupBy(identity) // s -> List(s,s)
.mapValues(_.size) // s -> 2
//.map( e => (e._1,e._2.length)) // s -> 2
.toList // (s,2)
// with tail recursion
def timesFirst(chars: List[Char]) : List[(Char,Int)] = {
@tailrec // comiler cheks if really tailrecursive
def timesTail(chars: List[Char], res: List[(Char,Int)]) : List[(Char,Int)] =
chars match {
case Nil => res // we are done when there are no characters left
case char :: rest => {
// otherwise
val newCharCount = res
.find (_._1 == char) //check if we already have seen the character
.map{ case (c,count) => (c,count + 1) } // if yes, we raise take the old count and raise it by one
.getOrElse( (char,1) ) // otherwise we count one occurrence
// here it gets recursive
timesTail(
rest, // remaining Characters
newCharCount :: res.filterNot(_._1 == char) // add the new count to list, remove old if present
)
}
}
// initial call with empty lsit to start the helper function
timesTail(chars,List())
}
// without tail recursion
def timesSecond(chars: List[Char]): List[(Char, Int)] = {
def incr(acc:Map[Char, Int], c:Char) = {
val count = (acc getOrElse(c, 0)) + 1
acc + ((c, count))
}
(Map[Char,Int]() /: chars)(incr).toList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment