Created
May 30, 2020 21:47
-
-
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
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.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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link to word.list file.