Program: Swapping characters to make anagrams


This program isn't in the book, but it uses several of the techniques described in Chapters 4-7 to jumble up and display a string, one character at a time.

You will be asked to enter a word. The program then repeatedly chooses two numbers at random, corresponding to the positions of characters in the word. The two characters are swapped around and the new word is displayed, one character at a time. When displaying the word, the program highlights the pair of swapped characters in green.


Select and copy the C++ source-code at the bottom of this post.

Paste into a text editor, such as Nano or Geany.


Then save the new file, ending in .cpp


I used anagram.cpp


To compile from the command-line:


    g++ -o anagram.cpp anagram


To run from the command-line:


    ./anagram


To speed the program up, reduce the value that the usleep() function uses - try 100


To slow it down, increase the value.


To increase the number of times the program jumbles up the word, change the value of MAX_JUMBLES at the start of the code.




Code is below...



#include <iostream> // To use screen output - cout, endl, flush
#include <cstdlib> // To use random() and srandom() functions
#include <ctime> // To "seed" random number generation using time
#include <unistd.h> // To use usleep() pause function



using namespace std; // Use standard namespace abbreviations


int main()
{
    const string GREEN = "\33[32m";
    const string NORMAL = "\33[0m";

    const int MAX_JUMBLES = 50;


    // Type in a word
    cout << "Type in a word: ";
    string word;
    cin >> word;
 
    int num1, num2, wordLen;
    char temp;

    // Find out how many symbols in word
    wordLen = word.length();



    // Use current time to as unpredictable random "seed"
    srandom( time(0) );



    // Jumble up the word certain number of times
    for (int loop = 0; loop < MAX_JUMBLES; loop++ )
    {
        // Choose 2 random numbers
        num1 = random() % wordLen;
        num2 = random() % wordLen;



        // Swap the letters at these positions
        temp = word.at(num1);
        word.at(num1) = word.at(num2);
        word.at(num2) = temp;



        // Display word, letter by letter, using different colours
        for ( int letter = 0; letter < wordLen; letter++ )
        {
            // Use green if it is a swapped letter
            if ( letter == num1  or letter == num2 )
                cout << GREEN;
            else
                cout << NORMAL;



            // Display single letter from word in the chosen colour
            cout << word.at(letter) << flush;



            // Pause for part of a second after displaying letter
            // REMOVE NEXT LINE FOR FULL SPEED PROGRAM!
            usleep(1000);

        } // end of word output

        // Move on to the next line of the display
        cout << endl;

    }  // end of for loop



    return 0;
}