Valerie Meunier

Valerie Meunier

  • 1.7k
  • 465
  • 21.1k

how to solve this with only one List?

Jun 19 2022 11:07 AM

Hi

yesratday, i posted a question about List<T> in a simulation of (soccer) matches. Each team plays against the orher teams . The winner gets 3 points and only 1 point when even.  

I got an answer from Ricardo Rigutini. He suggested to use a class and only one List instead of three. I tried his suggestion but i'm stuck when i have to give points to the winner of each match (points[i] += 3;). I wonder to do that without other List.

I show you the code so far ... Thansk for help.

using System;
using System.Collections.Generic;
using System.Linq;
class Oef16
{
    private class TeamScore
    {
        public string TeamName { get; set; }
        public int Score { get; set; }

        public TeamScore(string name)
        {
            TeamName = name;
        }

        public override string ToString()
        {
            if (Score < 10)
                return "0" + Score + " " + TeamName;
            else
                return Score + " " + TeamName;
        }
    }

    public static void Main()
    {
        int match;
        Random rand = new Random();
        List<TeamScore> teams = new List<TeamScore>
        { new TeamScore("team A"), new TeamScore("team B"), new TeamScore("team C")};

        List<int> points = new List<int> { };
        for (int i = 0; i < teams.Count; i++)
            points.Add(0);

        for (int i = 0; i <= teams.Count - 1; i++)
        {
            for (int j = i + 1; j <= teams.Count - 1; j++)
            {
                match = rand.Next(1, 4); // 1 = team A wins, 2 = team B wins, 3 = even
                switch (match)
                {
                    case 1:
                        points[i] += 3;
                        break;
                    case 2:
                        points[j] += 3;
                        break;
                    default:
                        points[i] += 1;
                        points[j] += 1;
                        break;
                }
            }
            Console.ReadLine();
        }
        int m = points.Max();
        int p = points.IndexOf(m);

        Console.WriteLine("Final ranking: the winner is " + teams[p] + " with " + points[p] + " points.");

        List<string> teampoint = new List<string> { };
        for (int i = 0; i < teams.Count; i++)
            teampoint.Add(" ");

        for (int i = 0; i <= teams.Count - 1; i++)
        {
            if (points[i] < 10)
                teampoint[i] = "0" + points[i] + " " + teams[i];
            else
                teampoint[i] = points[i] + " " + teams[i];
        }

        teams = teams.OrderBy(x => x.Score).ToList();
        teams.Reverse();

        foreach (string i in teampoint)
            Console.WriteLine(i);
    }
 


Answers (2)