## Programming Praxis – Word Cube

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: , , , , , , ,

### 7 Responses to “Programming Praxis – Word Cube”

1. Gav Says:

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…

2. Remco Niemeijer Says:

Sorry, it’s not a web app. If you want to use this program you’ll have to download Haskell and compile it yourself.

3. Gav Says:

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!

Given there’s none online, whoever did one might get a bit of web traffic though…

4. Mat Says:

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 ๐

5. Gav Says:

Woohoo!

Condiment! I knew it! Demonic? I’m quite happy I didn’t get that one ๐

Thanks ๐

6. Vaughn Says:

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.

7. Remco Niemeijer Says:

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.