Alphabetical Numbers


General Statement: Given a collection of integers, sort them alphabetically based on the words for these numbers.

Input: The first line in the data set is an integer that represents the number of data collections that follow. There are an unknown number of integers in each data collection. The integer 0 is used to indicate the end of the collection of integers.

Output: List the “sorted” integers in each collection on a separate line.
The output is to be formatted exactly like that for the sample output given below.

Assumptions: The maximum number of integers is 10.
The integers are in the range 1..19.
There are no duplicates within a data set.

Discussion: 1 2 3 4 would be sorted as 4 1 3 2. Four, one, three, and two are alphabetical.

Sample Input:
3
7 5 12 9 16 0
4 14 19 6 10 3 2 0
11 12 13 14 15 0

Sample Output:
5 9 7 16 12
4 14 19 6 10 3 2
11 15 14 13 12

Solutions :

#include <iostream>
#include <map>
using namespace std;

int main ()
{
    int dataset;
    cin >> dataset;

    map <string, int> m;

    //initialization
    m ["one"] = 1;  m ["two"] = 2;  m ["three"] = 3;
    m ["four"] = 4; m ["five"] = 5; m ["six"] = 6;
    m ["seven"] = 7;m ["eight"] = 8;m ["nine"] = 9;
    m ["ten"] = 10; m ["eleven"] = 11; m ["twelve"] = 12;
    m ["thirteen"] = 13; m ["fourteen"] = 14; m ["fifteen"] = 15;
    m ["sixteen"] = 16; m ["seventeen"] = 17;
    m ["eighteen"] = 18; m ["nineteen"] = 19;

    while ( dataset-- ) {

        int input;
        map <string, int>::iterator it;
        string str [20];
        int index = 0;

        while ( cin >> input && input ) {
            for ( it = m.begin (); it != m.end (); it++ ) {
                if ( (*it).second == input )
                    str [index++] = (*it).first;
            }
        }

        // sort sorting
        for ( int i = 0; i < index; i++ ) {
            for ( int j = i + 1; j < index; j++ ) {
                if ( str [i] > str [j] )
                    swap (str [i], str [j]);
            }
        }

        cout << m [str [0]];
        for ( int i = 1; i < index; i++ )
            cout << " " << m [str [i]];

        cout << endl;

    }

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s