Search code examples
cstringwords

Unscramble string in C


I am pretty new to C, and I thought I would try to make a program which unscrambles a string input to reveal a real word and I have it working, but with some words I get unexpected results. Here is an example of it working correctly:

Enter Word:stop

Match: opts
Match: post
Match: pots
Match: spot
Match: stop Match: tops

I am using a word list that I got from a program called "aspell" which allowed me to create a file full of words. What's strange is when I enter a word like "test" or "football" the response brings back words that have letters that don't originally exist in the input word. What am I doing wrong here? The following is my unscrambleWord function, which does most of the work. Also, I will post the "football" example

int unscrambleWord(int fgLetters) {

        // integer used for the counter
        int i = 0;

        // first make sure that the lengths of the word and of the list word is the same
        if(strlen(currentLine) == strlen(input)) {

                // loop through each letter in the word given
                for(i = 0; i < strlen(input); i++) {

                        // search the line for the current letter, if we find it increment fgLetters
                        if(strchr(currentLine, input[i]) != NULL)
                                fgLetters++;

                } // end for

                // once we have finished looping through the word; evaluate fgLetters
                if(fgLetters == strlen(input)) {

                        // fgLetters will be equal to the length of the word if each letter appears in the word
                        printf("\tMatch: %s \n", currentLine);

                } // end if - evaluate length of fgLetters

        }

    // return the fgLetters after we have possibly incremented it
        return fgLetters;

}

Here is the football example:

Enter Word:football

Match: blastoff 
Match: boastful 
Match: flatboat 
Match: football 
Match: lifeboat 
Match: softball 

For some reason, there are s's in the match strings, but the number of characters seem to be the same.


Solution

  • This algorithm gives false positives.

    Every letter of the word football is in the word softball. But that doesn't mean you can reorder the letters to change the word. You match the two os to the same o letter.

    An easy way to find matches is to sort the letters and see that you get the same word.

    football -> abflloot
    softball -> abfllost