theoretisch theoretisch - 2 months ago 30
Scala Question

count char frequency in string with scala

I search a way to count the different chars from a string.
The problem is that's not allowed to use any functions from the scala-api or to use vars (only val).

I want same result like that

val fruit: String = "dasisteintest"
Map(e -> 2, s -> 3, n -> 1, t -> 3, a -> 1, i -> 2, d -> 1)

In every try I made, I have at the end a
where I have to change the Int. But because it's an immutable list I can't change it.
How can I implement that counting char algorithm?


Here is the expected code. First the function which returns the char from the list

    def removeFromList(l: List[Char], l2: List[Char], toDelete: Char): List[Char] = {
       if (l.isEmpty) l2
       else {
           if (l.head == toDelete)
              removeFromList(l.tail, l2, toDelete)
              removeFromList(l.tail, l2 :+ l.head, toDelete)

and then the function which counts the chars and calls removeFromList()

def zaehlZeichen(s: String): List[(Char, Int)] = {
    val sl: List[Char] = s.toUpperCase().toList
    if (sl.isEmpty) Nil
    else {
      val l: List[Char] = List()
      val tupleList: List[(Char, Int)] = List();
      val in: Int = countChar(sl, 0, sl.head)
      val t: List[(Char, Int)] = tupleList :+ (sl.head, in)
      val cutL: List[Char] = removeFromList(sl, l, sl.head)
      t ::: zaehlZeichen(cutL.mkString);