home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.sources.wanted
- Path: sparky!uunet!usc!sol.ctr.columbia.edu!news.unomaha.edu!cwis!mfuhr
- From: mfuhr@cwis.unomaha.edu (Michael Fuhr)
- Subject: Re: anagram
- Message-ID: <mfuhr.727843735@cwis>
- Sender: news@news.unomaha.edu (UNO Network News Server)
- Organization: University of Nebraska at Omaha
- References: <EDSTROM.93Jan23152334@Elmer.hsc.ucalgary.ca>
- Distribution: comp
- Date: Sun, 24 Jan 1993 02:48:55 GMT
- Lines: 65
-
- edstrom@Elmer.hsc.ucalgary.ca (John Edstrom) writes:
-
- >I'm looking for a program that will take an input string of characters
- >or letters and output a list of legal words and phrases that can be
- >constructed from the letters in the input.
-
- I came up with a quickie perl program that does words; phrases are going
- to be a lot harder. The perl program is a bit slow - 20 secs or so on my
- machine to try everything in /usr/dict/words (about 25k words). A C program
- would be almost as simple and probably faster, but the machine I'm on isn't
- intended for programming and won't allow me to use cc.
-
- Everything between here and my .signature is the program.
-
- #!/usr/local/bin/perl
- #
- # anagram - Print a list of words that an anagram represents.
- #
- # Usage: anagram <characters>
- #
- # Run with the characters in the anagram as the argument. For example:
- #
- # anagram lkea
- #
- # The above invocation will produce the following output:
- #
- # kale
- # lake
- # leak
- #
- # The program first sorts the characters in the anagram specified on the
- # command line (e.g., the string "lkae" becomes "aekl"). It then reads
- # each word in the dictionary, sorts the characters in the word, and
- # compares it with the sorted anagram. Any match is printed.
-
-
- $dictionary = "/usr/dict/words"; # system dictionary - change if
- # necessary
-
- # subroutine sortchars
- #
- # Argument is a string. Returns a string containing the same characters
- # as the argument, but sorted.
- sub sortchars {
- join('', sort split(//, $_[0]));
- }
-
- # Print usage message if user entered wrong number of arguments.
- chop ($progname = `basename $0`);
- die "Usage: $progname word\n" unless (@ARGV == 1);
-
- # Sort the characters in the anagram.
- $charlist = &sortchars($ARGV[0]);
-
- # Read words from dictionary and print those that can be represented by
- # the anagram.
- open(DICT, $dictionary) || die "$dictionary: $!\n";
- while (<DICT>) {
- chop;
- print $_, "\n" if ($charlist eq &sortchars($_));
- }
- close(DICT);
- --
- Michael Fuhr
- mfuhr@cwis.unomaha.edu
-