reset password
Author Message
rabbott
Posts: 1649
Posted 17:34 Nov 06, 2012 |

Today I was asked about the final anagrams function.  Here's mine.

def sentenceAnagrams(sentence: Sentence): List[Sentence] = {
 
    def occurrenceAnagrams(occurrences: Occurrences): List[List[Word]] = {
 
      if (occurrences.isEmpty) List(Nil)
      else {
        val combs: List[Occurrences] = combinations(occurrences)
 
        for {
          occ: Occurrences <- combs
 
          val prefixWordsList: List[Word] = dictionaryByOccurrences.getOrElse(occ, Nil)
          if (!prefixWordsList.isEmpty)
 
          val remaining: Occurrences = subtract(occurrences, occ)
          val remainingWordsLists: List[List[Word]] = occurrenceAnagrams(remaining)
 
          prefixWord <- prefixWordsList
          remainingWords <- remainingWordsLists
 
        } yield prefixWord :: remainingWords 
      }
    }
 
    occurrenceAnagrams(sentenceOccurrences(sentence))
  }
Last edited by rabbott at 17:37 Nov 06, 2012.
Eric Liao
Posts: 158
Posted 17:55 Nov 06, 2012 |

here is mine: 

 

def sentenceAnagrams(sentence: Sentence): List[Sentence] = {
    def sentenceAnagrams0(occurs: Occurrences): List[Sentence] = occurs match {
      case Nil => List(Nil)
      case _ => {
        for {
        x <- combinations(occurs)
        y <- dictionaryByOccurrences.getOrElse(x, Nil)
        z <- sentenceAnagrams0(subtract(occurs, x))
        } yield List(y) ++ z
      }
    }
    sentenceAnagrams0(sentenceOccurrences(sentence))
  }
rabbott
Posts: 1649
Posted 21:13 Nov 06, 2012 |

Very good! Your is much cleaner.