Posts Tagged ‘cube’

Programming Praxis – Word Cube

July 13, 2010

In today’s Programming Praxis exercise our task is to write a program to solve Word Cube puzzles, in which you need to find as many words as possible that you can make from nine given letters. The provided Scheme solution is 21 lines, let’s see if we can do better.

Some imports:

import Data.Char
import Data.List

There are three criteria for valid solutions: the word must be at least 4 characters, it must contain the letter in the center and you must be able to make it from the nine letters.

solve :: String -> [String] -> [String]
solve c = filter (\w -> length w > 3 && elem (c !! 4) w && null (w \\ c))

All that’s left to do is load the dictionary, pass it to the solve function and print the results.

wordcube :: String -> IO ()
wordcube cube = mapM_ putStrLn . solve cube .
                lines . map toLower =<< readFile "words.txt"

Straightforward enough. A quick test to see if everything is working correctly:

main :: IO ()
main = wordcube "ncbcioune"

Yup. Not bad at one seventh the size of the Scheme solution.