list - Function always return Nil -
i trying resolve anagrams assignments. , can't figure out problem behind getting list() when running sentenceanagrams function. !
type word = string type sentence = list[word] type occurrences = list[(char, int)] def combinations(occurrences: occurrences): list[occurrences] = occurrences match { case nil => list(nil) case x :: xs => (for {z <- combinations(xs); <- 1 x._2} yield (x._1, i) :: z).union(combinations(xs)) } def subtract(x: occurrences, y: occurrences): occurrences = { if (y.isempty) x else { val ymap = y.tomap withdefaultvalue 0 x.foldleft(x) { (z, i) => if (combinations(x).contains(y)) { val diff = i._2 - ymap.apply(i._1) if (diff > 0) z.tomap.updated(i._1, diff).tolist else z.tomap.-(i._1).tolist } else z } }}
--
def sentenceanagrams(sentence: sentence): list[sentence] = { def sentenceanag(occ: occurrences): list[sentence] = if (occ.isempty) list(list()) else (for { comb <- combinations(occ) word <- (dictionarybyoccurrences withdefaultvalue list()).apply(comb) othersentence <- sentenceanag(subtract(occ, comb)) } yield word :: othersentence).tolist sentenceanag(sentenceoccurrences(sentence)) }
Comments
Post a Comment