Dec 23 2007

perl: Word Search Generator

Published by steve at 11:26 am under Programming

Intro

I enjoy doing puzzles, and find myself picking up these variety puzzle magazines to give myself something to do while sitting on the beach during vacation. And eventually I end up thinking about how they create these different types of puzzles, and wondering if I can come up with a way to create them myself.

Everyone is familiar with word search puzzles. A grid is filled with seemingly random letters, and a list of words is given. Your job is to find the words hidden in the grid. In this post I'm going detail a program to generate word search puzzles. The language I used is perl 5. Features of the program will be:

  • will run locally on a PC; from the command line (this is not a web application)
  • will generate puzzles of various sizes
  • words can be hidden in various directions
  • output will be a PDF file, which can be viewed or printed

As a disclaimer; my word search program is undoubtedly not the most clever way of solving this problem. My perl code is not the cleanest, nor is it the most reusable. And there are others who have already solved this problem - as usual there is a perl module out there that does it already! But there is a certain level of satisfaction that comes with thinking through it yourself - which was my motive here.

If you want to run the program yourself, you'll need to install perl. You'll also need one extra perl module; PDF::Create. You will find that ActiveState perl has good tools which allow you to add this module.

In the following discussion I'll show pieces of the perl code, with comments. You may want the full source code itself. Here it is, right-click to save as.

  • ws.pl - the perl source code (rename to ws.pl)
  • animals.txt - a sample configuration file

We will start by working out the logic needed....

Pages: 1 2 3 4 5 6 7

2 responses so far

2 Responses to “perl: Word Search Generator”

  1. Jack A Milleron 27 Feb 2009 at 7:50 pm

    Steve,
    Nice Work! I went through the same exercise in VB awhile ago and came up with the same logic except in one area. I even copped out with a “maximum tries=100″ like you did, but I didn’t consider it a cop out. The one thing I did different was to sort the words by the length of the word before I put them in the puzzle. My logic was that it was easier and hence more successful to place the longest word first. And it follows that the shortest words would be squeezed in at the end. I found that I had very few failures in placing words.
    Jack

  2. steveon 02 Mar 2009 at 1:36 pm

    Thanks for the comment Jack! I never thought of that, but yes trying to place the longest word first is certainly a good idea.

Trackback URI | Comments RSS

Leave a Reply