Skip to content

Instantly share code, notes, and snippets.

@douglasjose
Created May 30, 2020 21:47
Show Gist options
  • Save douglasjose/f269c60c4f8e17c1c4edb6c551c8be93 to your computer and use it in GitHub Desktop.
Save douglasjose/f269c60c4f8e17c1c4edb6c551c8be93 to your computer and use it in GitHub Desktop.
Finds valid words in a dictionary based on all permutations of valid characters
import scala.io.Source
object WordFinder {
// All permutations of the characters in the string
def permutations(s: String): List[String] = s.toSeq.permutations.map(_.unwrap).toList
// All distinct substrings obtained by removing one character from the original string
def subsets(s: String): List[String] = {
if (s.length == 1) List(s) else {
for (i <- 0 until s.length) yield removeChar(s, i)
}.toList.distinct
}
// Removes the i-th character from the string
def removeChar(s: String, i: Int): String = s.take(i).concat(s.drop(i + 1))
// All distinct permutations with length `minLength` or more of the string `s`
def allPermutation(s: String, minLength: Int): List[String] = {
if (s.length == minLength) permutations(s) else {
permutations(s) ++ subsets(s).flatMap(allPermutation(_, minLength)).distinct
}
}
// Iterates over all lines in the dictionary
def wordFile(): Iterator[String] = Source.fromInputStream(getClass.getResourceAsStream("/word.list")).getLines()
// List of permutations of the string `s` or its substrings of length >= `minlength` that exist in the dictionary
def solve(s: String, minLength: Int): List[String] = {
val combinations = allPermutation(s, minLength).toSet
wordFile().filter(combinations.contains).toList
}
}
@douglasjose
Copy link
Author

Link to word.list file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment