C 中的二元优胜者树

问题描述 投票:0回答:0

我的项目与举办网球比赛有关。首先,它要求用户输入玩家人数,并根据该人数进行锦标赛的一些阶段。

例如8人,则分3个阶段。 在第一阶段,玩家将两两对战,用户将选择每场比赛的获胜者。然后,获胜者需要进入第二阶段,获胜者之间将进行比赛,直到比赛中出现获胜者。

问题是代码在第一阶段和第二阶段都可以正常工作,但是当进入第三阶段或更多阶段时,它不会打印正确的获胜者姓名。在 cdebugger 的帮助下,我知道问题与更新函数和 winner_order 有关,我尝试了不同的方法来解决这个问题,但都没有奏效。

typedef struct {
    int player_num;
    int num_beaten;
    int *beaten;
} Player;

typedef struct {
    int num_players;
    Player *players;
} Stage;


void updateStage(Stage *curr_stage, Stage *next_stage, int match_num, int winner_num, int *winners_order, int *num_winners, int *next_player_index) {
    Player *winner = &curr_stage->players[winner_num - 1];
    winners_order[*num_winners] = winner_num;
    (*num_winners)++;
    next_stage->players[*next_player_index] = *winner;
    (*next_player_index)++;
}

// Play all the stages
for(int i = 0; i < num_stages; i++) {
    printf("\n\nStage %d:\n", i+1);

    Stage *curr_stage = stages[i];
    Stage *next_stage = stages[i+1];

    // Play matches in the current stage
    int num_matches = curr_stage->num_players / 2;
    int winners_order[num_matches];
    int num_winners = 0;
    int next_player_index = 0; // index of the next available position in the player array of the next stage
    for(int j = 0; j < num_matches; j++) {
        printf("\nMatch %d: Player %d vs Player %d\n", j+1, curr_stage->players[j*2].player_num, curr_stage->players[j*2+1].player_num);
        // Get the winner of the match
        int winner_num;
        printf("Enter the player number who won this match: ");
        scanf("%d", &winner_num);
        updateStage(curr_stage, next_stage, j+1, winner_num, winners_order, &num_winners, &next_player_index);
    }

for(int j = 0; j < num_winners; j++) {
    int winner_num = winners_order[j];
    next_stage->players[j] = curr_stage->players[winner_num-1];
}
}
c pointers data-structures tree binary
© www.soinside.com 2019 - 2024. All rights reserved.