Search code examples
arraysclogic

Logic error in function to search for highest scoring player(s) in a game


I am writing a function to search through an array that stores the score of some players for the highest scoring player(s). The problem is that the I can search and record the highest score easily but it is when there are multiple of a score that my logic falls appart.

My code is attached below:

/* Function display_highest_score() searches the player score array for the highest value and
   any repetitions before printing the results to the screen.
   Parameters: The player array, score array, and number of players.
   Returns: Nothing.*/
void display_highest_score(char player_array[][STRING_LENGTH], int score_array[], int num_players) {

    int high_num = 0; /* Stores the highest player score. */
    int position[MAX_PLAYERS] = { 0 }; /* Stores the position of the player(s) with the highest score. */
    int players = 1; /* Stores the number of players that have that score. */
    int j = 0; /* A looping variable. */

    /* Loop to find and store the highest scoring player(s). */
    for (int i = 0; i < num_players; i++) {

        if (high_num < score_array[i]) {

            high_num = score_array[i];
            position[j] = i;
            j++;

        }
        else if (high_num == score_array[i]) {

            players = players++;

        }

    }

    /* Print to screen code. */
    printf("\nPlayers with the highest score of %d are:\n\n", high_num);

    for (j = 0; j < players; j++) {

        printf("--> %s\n", player_array[position[j]]);

    }

}

If the function is searching through an array, say score_array[10] = { 3, 1, 0, 10, 4, 8, 10, 0, 3, 16 } then it will change the maximum score to 16 but it will print the players that have score 10 as having 16 instead.

I've tried to swap the position[j] = i; j++; segment to the else if statement but it still doesnt work

I'm still relativley new to c coding so any help would be appreciated.


Solution

  • You need to add the current position in all cases, but clear the previously stored positions when a new high score is found. Also, you should initialize players to 0 to handle the corner case of an empty set of players (in any case, you should print an error message in case players==0 at the end):

        int players = 0;
    
    ...
        if (high_num <= score_array[i]) {
            if (high_num < score_array[i]) {
                 high_num = score_array[i];
                 players = 0;
            }
            position[players++] = i;
        }
    ...