Last active
February 3, 2018 18:55
-
-
Save jlandahl/6971bcd9b8b0d96a8860f70a856eeea5 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
object Scrabble extends App { | |
import scala.io.Source | |
val words = Source.fromFile("/usr/share/dict/words").getLines.toStream | |
val primes: Stream[Int] = | |
2 #:: Stream.from(3, 2).filter(i => primes.takeWhile(p => p * p <= i).forall(p => i % p > 0)) | |
val letterCounts = words.foldLeft(Map.empty[Char, Long].withDefault(_ => 0L)) { case (counts, word) => | |
word.toLowerCase.filter(_.isLetter).foldLeft(counts) { case (counts2, c) => | |
counts2.updated(c, counts2(c) + 1) | |
} | |
} | |
val charPrime = letterCounts.toSeq.sortBy(-_._2).map(_._1).zip(primes).toMap | |
def stringPrime(s: String): Long = | |
s.toLowerCase.filter(_.isLetter).foldLeft(1L) { case (a, c) => a * charPrime(c) } | |
def search(tiles: String, words: Seq[String]): Seq[String] = { | |
val tilesPrime = stringPrime(tiles) | |
words | |
.filter(_.length <= tiles.length) | |
.filter(word => tilesPrime % stringPrime(word) == 0) | |
} | |
search("abcdefghi", words).foreach(println) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment