Ranking Scores – Solution

This month’s Exercise is to create an array of six players, assign each a random score (1 to 100), then display the player’s scores by rank. The first problem you most likely encountered was how to keep the player’s number and score together.

For my solution, I chose to create an array of structures as opposed to an array of integers. That way, the player number and their score are bound as members within a structure. This solution became obvious because the alternative is to create an integer array. The problem with that solution is associating the array element offset with the score. Rather than mess with all that logic, a structure like this works better:

struct p {
    int number;
    int score;
};

After creating array players[] of structure p, I use a for loop to fill each structure with the player number and a random score, 1 to 100.

The final part of the code sorts the structure based on the player[].score member. I used a simple bubble sort. And the sort swap works with structure variables directly, so I didn’t need to mess with pointers.

Here is the code for my solution:

/* seed the randomizer */
    srand( (unsigned)time(NULL));

    /* assign each player a number and score 1 to 100 */
    for(x=0;x<PLAYERS;x++)
    {
        player[x].number = x + 1;
        player[x].score = rand() % 100 + 1;
    }

    /* sort the scores */
    for(x=0;x<PLAYERS;x++)
        for(y=x+1;y<PLAYERS;y++)
            if(player[x].score < player[y].score)
            {
                temp = player[x];
                player[x] = player[y];
                player[y] = temp;
            }

    /* display the results */
    puts("Round Results:");
    for(x=0;x<PLAYERS;x++)
        printf("#%d Player %d, score %d\n",
                x+1,
                player[x].number,
                player[x].score);

    return(0);
}

The output looks like this:

Round Results:
#1 Player 2, score 95
#2 Player 6, score 63
#3 Player 5, score 60
#4 Player 4, score 55
#5 Player 3, score 36
#6 Player 1, score 16

If you want to get fancy, you could change structure p member number to a string and assign names to the players. I indulge you to attempt this modification on your own. As a hint: Use pointers. You can click here to view my solution.

Leave a Reply