Алгоритм C - кто победитель команды - PullRequest
0 голосов
/ 04 марта 2019

Мне нужно хранить данные из турнира.Мне нужно знать, сколько команд сыграют (n) и сколько игр они сыграют (n!).Затем имена команд и их результаты.Примерно так:

Input: 
3 6
TeamX
TeamY
TeamZ
TeamX 0 - TeamY 3
TeamX 1 - TeamZ 0
TeamY 1 - TeamX 0
TeamY 0 - TeamZ 0
TeamZ 0 - TeamX 0
TeamZ 3 - TeamY 1

Вывод будет примерно таким:

This winner is TeamY, with 7 point(s)
Won 2 game(s), tied 1 game(s) e lost 1 game(s)
Scored 5 goal(s) e suffered 3 goal(s)

РЕДАКТИРОВАТЬ 2: ЭТО то, что у меня есть до сих пор.Но это не сработает на scanf .... Я не могу напечатать названия команд после количества команд и игр.Можете ли вы запустить его и попытаться понять?


Руководство: у меня есть игровые и командные структуры, сначала я добавляю названия команд в массив команд, затем добавляю игры в массив игр.Затем, если / else блокирует подсчет выигрышей, проигрышей и т. Д. И, наконец, видит и печатает победителя.

#include <stdio.h>
#include <string.h>

struct game {
  const char *teamA;
  int scoreA;
  const char *teamB;
  int scoreB;
};

struct team {
  const char *teamA;
  int score;
  int wins;
  int losses;
  int ties;
  int scored;
  int suff;

};

struct team team_new(const char *teamA, int score, int wins, int losses, int ties, int scored, int suff)
{
  struct team t;
  t.teamA = strdup(teamA);
  t.score = score;
  t.wins = wins;
  t.losses = losses;
  t.ties = ties;
  t.scored = scored;
  t.suff = suff;

  return t;
};

struct game game_new(const char *teamA, int scoreA, const char *teamB, int scoreB)
{
  struct game g;
  g.teamA = strdup(teamA);
  g.scoreA = scoreA;
  g.teamB = strdup(teamB);
  g.scoreB = scoreB;
  return g;
};

int main(void)
{

  int i, j, teams, nrgames, biggestScore, whichTeam;

  scanf("Teams and number of games %d %d", &teams, &nrgames);

  //add team names to theTeamss struct
  struct team theTeams[teams];
  size_t num_teams = 0;
  for (i = 0; i < teams; ++i)
  {
    char teamA[20];
    if (scanf("%s", teamA) != 1)
      exit(0);
    theTeams[++num_teams] = team_new(teamA, 0, 0, 0, 0, 0, 0);
  }


  struct game games[nrgames]; //add games
  size_t num_games = 0;
  for (i = 0; i < sizeof games / sizeof *games; ++i)
  {
    char teamA[20], teamB[20];
    int scoreA, scoreB;
    if (scanf(" %s %d - %s %d", teamA, &scoreA, teamB, &scoreB) != 4)
      exit(0);
    games[++num_games] = game_new(teamA, scoreA, teamB, scoreB);
  }


     //run through games[] to change values of theTeams[] scores

  //games - A against B
  for (i = 0; i < sizeof games / sizeof *games; ++i)
  {
    for (j = 0; j < sizeof theTeams / sizeof *theTeams; ++j)
    {
      if ((games[i].teamA == theTeams[j].teamA)) //team(A)
      {
        //if A wins
        if(games[i].scoreA > games[i].scoreB)
        {
          theTeams[j].score += 3;
          theTeams[j].wins += 1;
          theTeams[j].scored = games[i].scoreA;
        }
        //if A loses
        else if (games[i].scoreA < games[i].scoreB)
        {
          theTeams[j].score += 0;
          theTeams[j].losses += 1;
          theTeams[j].suff = games[i].scoreB;
        }
        else //tied
        {
          theTeams[j].score += 1;
          theTeams[j].ties += 1;
          theTeams[j].suff = games[i].scoreA;
        }
      }

      if ((games[i].teamB ==  theTeams[j].teamA))//team(B)
      {
        //if B wins
        if(games[i].scoreB > games[i].scoreA)
        {
          theTeams[j].score += 3;
          theTeams[j].wins += 1;
          theTeams[j].scored = games[i].scoreB;
        }
        //if B loses
        else if (games[i].scoreB < games[i].scoreA)
        {
          theTeams[j].score += 0;
          theTeams[j].losses += 1;
          theTeams[j].suff = games[i].scoreA;
        }
        else //tied
        {
          theTeams[j].score += 1;
          theTeams[j].ties += 1;
          theTeams[j].suff = games[i].scoreB;
        }
      }
    }
  }


  //accessing to the winner team
  biggestScore = theTeams[0].score;
  whichTeam = 0;
  for (i = 0; i < sizeof theTeams / sizeof *theTeams; ++i){
    if (theTeams[i].score > biggestScore){
      biggestScore = theTeams[i].score;
      whichTeam = i;

    }
  }

  //output
  printf("\n This winner is %s, with %d point(s), Won %d game(s), tied %d game(s) and lost %d game(s), Scored %d goal(s) e suffered %d goal(s)\n", theTeams[whichTeam].teamA, theTeams[whichTeam].score, theTeams[whichTeam].wins, theTeams[whichTeam].losses, theTeams[whichTeam].ties, theTeams[whichTeam].scored, theTeams[whichTeam].suff);

  return 0;
}

Ответы [ 2 ]

0 голосов
/ 04 марта 2019

C, как и все языки программирования, хорош только в той степени, в которой вы составили план моделирования данных.

. Для этого может работать массив массивов, в котором хранятся данные.

Возможнохочу также рассмотреть базу данных для отношений на основе команд.Затем вы также можете добавить метаданные и тому подобное (например, метки времени).Хотя хорошо, если вы не возражаете против использования приложения за пределами C.

0 голосов
/ 04 марта 2019

Нет проблем с языком Си и строками;ты можешь делать все, что захочешь.Это просто немного больше ответственности, чем в других языках.

Кажется, вам нужен массив структур, да.Я бы порекомендовал смоделировать его как набор игр, где каждая игра записывает команды, которые принимали участие, и их результаты.Нет необходимости сначала записывать список «доступных» команд, проще потом извлечь его из данных игры.

struct game {
  const char *teamA;
  int scoreA;
  const char *teamB;
  int scoreB;
};

struct game game_new(const char *teamA, int scoreA, const char *teamB, int scoreB)
{
  struct game g;
  g.teamA = strdup(teamA);
  g.scoreA = scoreA;
  g.teamB = strdup(teamB);
  g.scoreB = scoreB;
  return g;
}

, а затем в программе man:

int main(void)
{
  struct game games[100];
  size_t num_games = 0;
  for (size_t i = 0; i < sizeof games / sizeof *games; ++i)
  {
    char teamA[100], teamB[100];
    int scoreA, scoreB;
    if (scanf(" %s %d - %s %d", teamA, &scoreA, teamB, &scoreB) != 4)
      break;
    games[++num_games] = game_new(teamA, scoreA, teamB, scoreB);
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...