CSCI 3333.3 Data Structures
Spring 2013
Suggested Solution to Homework #3

(1) A possible algorithm:

Function Anagram(word: string, dictionary_name: string):

Input:
   word: the word of interest for finding anagrams; only accept alphabets
   dictionary_name: a text dictionary file name that stores a word per line
Output:
   result: a list of all anagrams of word
Note: checking of anagrams is performed in a case insensitive manner.
  
Algorithm:

in_word <- convert_to_lower_case(word);
in_word_char_array <- split in_word into characters;
sort(in_word_char_array);
in_word_sorted <- join the characters in in_word_char_array;
  
result <- ();    // empty list
  
open(dictionary, dictionary_name);
  
while (line <- read a line from dictionary) {
    current_word <- remove any end of line symbol from line
  
   if current_word and in_word is the same word {
       //  skip the current word
      next;
   }
   //  if current_word is an anagram of in_word then
    //       append current_word to result;
   current_word <- convert_to_lower_case(current_word);
   current_word_char_array <- split current_word into characters;
   sort(current_word_char_array);
    current_word_sorted <- join the characters in current_word_char_array;  
  
    if curr_word_char_array and in_word_char_array is identical {
       append current_word to result;
   }
}

return result;

(2) In Perl (lightly documented):

use strict;

#    anagram.pl
#
#    Print all anagrams of a word.
#    Usage: anagram.pl word
#     

#   Get input word
@ARGV >= 1 || die "usage: anagram.pl word";
my $inWord = $ARGV[0];

#   Check that the word contains only alphabet
die "The word can only contain alphabets.\n" if ($inWord =~ /[^a-zA-Z]/);

# sorted in word in lower case.
my $sortedInWord = join('',sort(split(//, lc($inWord)))); 
my @result = ();

#  Find and print anagrams
open(DICT, "words.txt") || die "Can't open words.txt";
my $word;
while ($word = <DICT>)
{  chomp($word);
   $word = lc($word);
   next if $word eq $inWord;   # skip the word itself
   #  if the word is an anagram, append it to the result.
   if ($sortedInWord eq join('',sort(split(//, $word)))) {
       push @result, $word;
   }
}
close(DICT);

#   show result.
if (@result == 0) {
   print "The word $inWord has no anagram.\n";
}
else {
   print "The word $inWord has ";
   if (scalar @result > 1) {
       print scalar @result, " anagrams: ";
   }
   else {
       print scalar @result, " anagram: ";
   }
   print join (', ', @result);
   print ".\n";
}
exit 0;