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.
Tags: bonsai, code, cube, Haskell, kata, praxis, programming, word
July 14, 2010 at 2:22 am |
Hey mate – did you upload this to a web app anywhere? I’m stuck on a word cube and wanted to solve it!
Can’t find an online one anywhere…
July 14, 2010 at 8:09 am |
Sorry, it’s not a web app. If you want to use this program you’ll have to download Haskell and compile it yourself.
July 14, 2010 at 8:28 am |
I don’t even know what Haskell is (I’m sure I could google it) but it doesn’t really seem like something I’d be able to do!
Thanks for the reply anyway.
Given there’s none online, whoever did one might get a bit of web traffic though…
July 19, 2010 at 11:17 am |
Hi Remco,
That’s some nice code you have there, much neater than my own method of solving the wordcubes, but I was using python not haskell
http://www.stealthcopter.com/blog/2009/12/python-wordwheel-wordcube-solver/
Also for gav I have made a web application for solving the wordcubes (or whatever other brand of polygon puzzle) on my website:
http://www.stealthcopter.com/tools/anagram.php
Enjoy
Mat
July 19, 2010 at 11:25 am |
Woohoo!
Condiment! I knew it! Demonic? I’m quite happy I didn’t get that one
Thanks
July 19, 2010 at 8:36 pm |
I’m not sure that this quite meets the word cube constraints. This solution allows you to repeat any of the letters in the cube as many times as necessary, while you should be limited to using them just the number of times that they appear in the cube.
July 20, 2010 at 7:17 am |
No, this version works correctly. For example, the output for the example wordcube doesn’t include the word “noon”, since we only have one o. The reason for this is the use of the list difference operator (\\). If a word uses more than the available amount of a certain letter, the difference will not be empty (e.g. “aaa” \\ “aa” == “a”), and hence will be filtered out.