On 11 Mar 2007 10:54:38 -0700 in comp.lang.c++,
theronnightstar@gmail.com wrote,
Quote:
>I am writing an anagram program for my fiance. Figured it would be an
>excellent task to learn from.
I'm afraid I did not figure out exactly what is not working in your
code, but maybe I can make some suggestions.
You start with std::string holding your word. That's very good, I'd
stick with that and use nothing but std::string to hold your words and
anagrams. No char arrays, no int vectors. Don't forget string supports
operator[] and a lot more.
Next, your nested loops. Too complicated. Say you have two strings and
you wish to do something depending on the relationship between them.
That would look like
if (adverb(game_word, test_word)) {
where adverb() is a small function you supply (with an appropriate name)
that encapsulates the relationship you are looking for and gives it a
name. Unless, of course, the relationship is pre-coded like
string::operator==(). Not some inline loop looking char-by, leading to
hundred-line functions with nested loops six levels deep.
Working with anagrams you almost always encounter a point where it is
useful to sort the characters of a word; for example that allows you to
easily check if one word is an anagram of another. A function that does
that:
std::string sorted(std::string const & word)
{
std::string result(word);
std::sort(result.begin(), result.end());
return result;
}
Example usage:
bool anagram_match(std::string const &first, std::string const &second)
{
return sorted(first) == sorted(second);
}
Example usage of that:
if(anagram_match(game_word, test_word)) ...
Giving particles like that reasonable makes the code easier to
understand the bigger picture, and short functions make it easier to
tell if the code does what the name says,.