scala - Counting occurences of characters in a String using tail recursion -
i have no clue how count occurrences of characters in string using tail recursion in scala.
i need run programme input
times(explanation) and output is:
list((e,1), (x,1), (p,1), (l,1), (a,2), (n,2), (t,1), (i,1), (o,1)) i tried running rle far topic of tail recursion new me, steps/algorithm doing perfect
possible solutions:
a string list of characters. grouping them identity (x => x), count them. groupby returns map can transformed list of tuples tolist.
code/ not reinventing wheel
def times(s: string) = s.groupby(identity).mapvalues(_.size).tolist times: (s: string)list[(char, int)] example
times("explanation") res1: list[(char, int)] = list((e,1), (x,1), (n,2), (t,1), (a,2), (i,1), (l,1), (p,1), (o,1)) code tail recursion / reinvents wheel/ please utilize not cheat in coursera scala course
import scala.annotation.tailrec def mytimes(s: string) : list[(char,int)] = { @tailrec // comiler cheks if tailrecursive def timestail(chars: list[char], res: list[(char,int)]) : list[(char,int)] = chars match { case nil => res // done when there no characters left case char :: rest => { // otherwise val newcharcount = res. find (_._1 == char). //check if have seen character map{ case (c,count) => (c,count + 1) }. // if yes, raise take old count , raise 1 getorelse( (char,1) ) // otherwise count 1 occurrence // here gets recursive timestail( rest, // remaining characters newcharcount :: res.filternot(_._1 == char) // add together new count list, remove old if nowadays ) } } // initial phone call empty lsit start helper function timestail(s.tolist,list()) } scala tail-recursion
No comments:
Post a Comment