Last active
January 26, 2016 17:25
-
-
Save LyndonArmitage/453a4bb197a569636f32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.collection.mutable | |
// The word wheel data | |
val required = List[Char]('a') | |
val otherChars = List[Char]('t', 'n', 'd', 'o', 'e', 'c', 'i', 'u') | |
// Load a word list and remove anything smaller than 2 letters | |
val wordList = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/wordsEn.txt")) | |
.getLines() | |
.filter(_.length > 2) | |
/** | |
* @param word The word to order | |
* @return An ordered string of the input words characters | |
*/ | |
def sortWord(word: String) = word.toCharArray.sorted.mkString | |
// Define a hash map for storing ordered word strings to the original words | |
val toWords = mutable.HashMap[String, List[String]]() | |
// Take each word and map it to it's ordered counterpart | |
wordList.foreach(word => { | |
val ordered = sortWord(word) | |
if (toWords.contains(ordered)) { | |
toWords.put(ordered, toWords.get(ordered).get :+ word) | |
} else { | |
toWords.put(ordered, List[String](word)) | |
} | |
}) | |
// Generate all possible combinations of otherChars + the required characters | |
val allPossibles = Range(2, otherChars.length) | |
.flatMap(i => otherChars.combinations(i)) | |
.sortWith((left, right) => left.length > right.length) | |
.map(l => l.++(required)) | |
.map( s => sortWord(s.mkString)) | |
.iterator | |
// Get a flat list of the results | |
val results: Iterator[String] = allPossibles.flatMap(possible => { | |
toWords.get(possible) | |
}).flatten | |
// Print the results | |
results.toSeq.sortWith((left, right) => { | |
left.length > right.length | |
}).foreach(println) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Didn't realize there was a List.combinations method in Scala; could probably solve the issue with not supporting multiple characters using it.