Summary | Anagram Solver --
use a dictionary of words to find all anagrams of a given phrase |
Topics |
recursive backtracking |
Audience |
Intended for CS2 |
Difficulty |
Intermediate difficulty, one week assignment |
Strengths |
The greatest strength is that
students really love to run the program once it's done. They
particularly seem to love finding anagrams of names (their own
name, their friends' names, their relatives' names). It also
demonstrates how a complex task can be accomplished with a short
program (fewer than 50 lines) using a powerful programming
technique (recursive backtracking) and leveraging other components
(Map, ArrayList, a custom LetterInventory class). |
Weaknesses |
Because few lines of code are
required to solve the problem, there is greater possibility for students
to help each other too much. Also, the program can explode rather
quickly for longer phrases (taking too long to find answers and
producing too much output). |
Dependencies |
In this form, the assignment
assumes the existence of a class called LetterInventory that
handles the low-level character details. This can be given as
an earlier assignment, which makes this two assignments in one. |
Variants |
As with all backtracking
problems, this one can blow up quickly (run slowly, produce too
much output). There are many optimizations that can be
explored. One can also explore issues like limiting the output
(number of words, excluding one-letter words, etc). And it's
interesting to run the program with different dictionaries.
This also makes a great Prolog problem. |
I first wrote this assignment in Prolog for a comparative programming languages course where the students wrote about 15 lines of code on top of some basic utility code that I provided. For anyone interested in the Prolog version, I include:
I use the "8 queens" problem as an example in lecture where a Board class does most of the low-level work of keeping track of the placement of queens, allowing us to write concise backtracking code that does the actual search. Below are the source files:
Extra info about this assignment: