Scrabble
February 22, 2019
Today’s task is based on the game of Scrabble.
Your task is to write a program to find the dictionary words of length 2 to 7 that can be formed from the letters Q O F T H E A. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
@programmingpraxis: I see the letter S popping up in your results. Your code on ideone has an extra S.
In Python. All words without the S are printed
Assumes letters can be used multiple times
Python solution, sort letters and do an element by element comparison on the sorted letters:
A Haskell version using the dictionary on a Mac. (The letter ‘q’ doesn’t appear in the output.)
And here’s the same thing using egrep.
Then I saw @Globules elegant solution and realised that mine could be greatly simplified if I just tweaked the regexp.
and use it like this:
👏 to @Globules
This is supposed to be Scrabble so letters can’t be used more than once.
Here is a more Scrabble-conforming version, where each letter is used at most once.
Here’s a trie-based solution – read the set of words into a trie (using the sorted letters of each word for the trie entries, rather than the word itself). Then we can find subsets of the given letter multiset reasonably efficiently. Since it’s Scrabble, just consider all-lowercase words (no proper nouns allowed).
Common Lisp:
Common Lisp:
[sourcecode lang="lisp"]
(defun is-scrabble-word (word letters)
(and (<= 2 (length word) 7)
(every #'(lambda (c) (find c letters)) word)))
(defun filter-dictionary (path letters)
(with-open-file (in path)
(loop for line = (read-line in nil nil)
while line
when (is-scrabble-word (string-upcase line) letters) collect line)))
(defun print-scrabble ()
(format t “~{~a ~}” (filter-dictionary “/usr/share/dict/words” “QOFTHEA”)))
Here’s a solution in Python:
Output: