我有一个任务,我被它卡住了[类,数组,循环]

本文关键字:数组 循环 有一个 任务 | 更新日期: 2023-09-27 18:14:19

我的外语不是英语,但我会尽力做到最好。

*

正在进行电子邮件和服务器之间的传输。通过internet的接口速度可以从文件中得知。您需要列出在至少一个小时内没有获得任何数据的服务器。通过了解发件人发送电子邮件的时间,您可以计算电子邮件何时完全转移(发送)到服务器。如果(信件的)转帐在下一个小时内完成,那么这个小时也算。letters.csv(信件发送的时间,发件人,接收者,服务器名称,信件大小)servers.csv(服务器名称,速度(咬/秒))所有结果都必须放在。csv文件中。结果应该按照以下顺序书写:服务器名称,收到的信件,所有信件的总体大小,传输所有信件需要多长时间,服务器多长时间没有收到任何信件。所有的信都是在收到的同时发出的。

应该没有没有使用过的服务器。 *

letters.csv example

13:15:47; Gustas@inbox.lt; Justas@inbox.lt; Serveris_1; 5005:45:11; Tomas@inbox.lt; Simas@inbox.lt; Serveris_3; 4212:13:22; Mindaugas@inbox.lt; Justas@inbox.lt; Serveris_3; 607:15:42; Gustas@inbox.lt; Mindaugas@inbox.lt; Serveris_2; 1908:18:32; Jonas@inbox.lt; Tomas@inbox.lt; Serveris_1; 112

服务器。scv示例

Serveris_1; 15Serveris_2; 24Serveris_3; 3

我自己做的每一个例子!

namespace _1
{
    class Letters
    {
        public string Time { get; set; }
        private string Sender { get; set; }
        private string Receiver { get; set; }
        public string ServerName { get; set; }
        public int FileSize { get; set; }
        public Letters() { }
        public Letters(string time, string sender, string receiver, string servername, int filesize)
        {
            Time = time;
            Sender = sender;
            Receiver = receiver;
            ServerName = servername;
            FileSize = filesize;
        }
    }
    class Servers
    {
        public string ServerName { get; set; }
        public int Speed { get; set; }
        public Servers() { }
        public Servers(string servername, int speed)
        {
            ServerName = servername;
            Speed = speed;
        }
    }
    class Program
    {
        public const int Minute = 60;
        private const int MAX_LETTERS = 50;
        private const int MAX_SERVERS = 5;

        private static int AmmountOfLetters = 0;
        private static int AmmountOfServers = 0;
        static void Main(string[] args)
        {
            Letters[] letters = ReadLaiskaiData();
            Servers[] servers = ReadServersData();
            TransferToServers(letters, servers);

        }
        // Reikia sudaryti sąrašą serverių, į kuriuos nebuvo perduota nei vieno baito, kurios nors valandos bėgyje.
        /* PERDAVIMAS Į SERVERIUS   */
        private static void TransferToServers(Letters[] letters, Servers[] servers)
        {
            int speed = 0;
            int f_size = 0;
            int fileSizeLeft = 0;
            for(int i = 0; i < MAX_LETTERS; i++)
            {
                int valanda =  Int32.Parse(letters[i].Time.Substring(0, 2));
                fileSizeLeft = letters[i].FileSize;
                for(int k = valanda; k < (valanda + 24); k++)
                {
                    switch (letters[i].ServerName)
                    {
                        case "Serveris_1":
                        {
                            for (int m = 0; m < 60; m++)
                            {
                                speed = servers[i].Speed;
                                f_size = letters[i].FileSize;
                                fileSizeLeft = letters[i].FileSize - speed;
                                Console.WriteLine("{0}", f_size);
                                Console.WriteLine("{0}", fileSizeLeft);
                            }
                            break;
                        }
                        case "Serveris_2":
                        {
                            break;
                        }
                        case "Serveris_3":
                        {
                            break;
                        }
                    }
                }
                Console.WriteLine("{0}", valanda);
            }
        }
        /* SERVERIŲ SKAITYMAS IŠ FAILO  */
        private static Servers[] ReadServersData()
        {
            Servers[] servers = new Servers[MAX_SERVERS];
            using (StreamReader reader = new StreamReader(@"Serveris.csv"))
            {
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] values = line.Split(';');
                    string servername = values[0];
                    int speed = int.Parse(values[1]);
                    Servers server = new Servers(servername, speed);
                    servers[AmmountOfServers++] = server;
                    Console.WriteLine("{0} {1}", servername, speed);
                }
            }
            return servers;
        }
        /* LAIŠKŲ SKAITYMAS IŠ FAILO    */
        private static Letters[] ReadLaiskaiData()
        {
            Letters[] letters = new Letters[MAX_LETTERS];
            using (StreamReader reader = new StreamReader(@"laiskai.csv"))
            {   
                string line = null;
                while((line = reader.ReadLine()) != null)
                {
                    string[] values = line.Split(';');
                    string time = values[0];
                    string sender = values[1];
                    string receiver = values[2];
                    string servername = values[3];
                    int filesize = int.Parse(values[4]);
                    Letters letter = new Letters(time, sender, receiver, servername, filesize);
                    letters[AmmountOfLetters++] = letter;
                    Console.WriteLine("{0} {1} {2} {3} {4}", time, sender, receiver, servername, filesize);
                }
            }
            return letters; 
        }
    }
}

我甚至不知道我这样做是否正确。我不知道怎么计算。我希望我把任务翻译得可以理解。希望你们中有人能帮助我。

我有一个任务,我被它卡住了[类,数组,循环]

我已经提供了一个与你的例子长度相匹配的答案。它是彻底的,因为你提供了很好的证据来证明你已经尝试过了。我将在源代码区域下面激励一些决策。

class Letter
{
    public const char FieldSeparator = ';';
    public const char TimeFieldSeparator = ':'; //WARNING: Tweaking this will result in you needing to change .ToString() calls on TimeSpan and DateTime manually
    public DateTime SendDate { get; private set; }
    public DateTime EstimatedReceivedDate => SendDate + (Server != null ? TimeSpan.FromSeconds((double)Size / Server.TransferRate) : TimeSpan.MaxValue);
    //Traditionally, the server would record this data when it receives it
    public string Sender { get; private set; } //These should be fundamental User / Account classes
    public string Receiver { get; private set; }
    public Server Server { get; private set; }
    public int Size { get; private set; } //We assume this is the size in bytes
    public Letter(DateTime sendDate, string sender, string receiver, Server server, int size)
    {
        SendDate = sendDate;
        Sender = sender;
        Receiver = receiver;
        Server = server;
        Size = size;
    }
    public static Letter Deserialize(string s, IList<Server> servers)
    {
        if (string.IsNullOrEmpty(s)) throw new ArgumentException("Invalid argument s: Cannot parse from null or empty string");
        var split = s.Split(FieldSeparator);
        if (split.Length != 5) throw new ArgumentException("Malformed string s! Format: Time " + FieldSeparator + "Sender" + FieldSeparator + "Receiver" + FieldSeparator + "Server" + FieldSeparator + "Size");
        var date = DateTime.Today;
        var timeSplit = split[0].Split(TimeFieldSeparator);
        if (timeSplit.Length != 3) throw new ArgumentException("Malformed time in s! Format: HH" + TimeFieldSeparator + "mm" + TimeFieldSeparator + "ss");
        int hour;
        if (!int.TryParse(timeSplit[0], out hour)) throw new ArgumentException("Could not parse hour from string: " + timeSplit[0]);
        int minute;
        if (!int.TryParse(timeSplit[1], out minute)) throw new ArgumentException("Could not parse minute from string: " + timeSplit[1]);
        int second;
        if (!int.TryParse(timeSplit[2], out second)) throw new ArgumentException("Could not parse second from string: " + timeSplit[2]);
        date = date + new TimeSpan(0, hour, minute, second);
        if (servers == null || servers.Count == 0) throw new ArgumentException("Invalid list of servers passed. No servers mean no message could have been sent.");
        Server server;
        try
        {
            server = servers.First(serv => serv.Name == split[3]);
        }
        catch (InvalidOperationException)
        {
            throw new ArgumentException("Could not parse server from string: " + split[3] + ". No such server was present in the list passed to the function.");
        }
        int size;
        if (!int.TryParse(split[4], out size)) throw new ArgumentException("Could not parse size from string: " + split[4]);
        var letter = new Letter(date, split[1], split[2], server, size);
        server.Letters.Add(letter);
        return letter;
    }
    public string Serialize(Server s)
    {
        return s.ToString();
    }
    public override string ToString()
    {
        return SendDate.ToString("HH:mm:ss") + FieldSeparator + Sender + FieldSeparator + Receiver + FieldSeparator + Server.Name + FieldSeparator + Size;
    }
}
class Server
{
    public const char FieldSeparator = ';';
    public string Name { get; private set; }
    public int TransferRate { get; set; } //Bytes/Sec
    public IList<Letter> Letters { get; private set; }
    public int BytesReceived => Letters.Sum(l => l.Size);
    public int TotalTransferTime => BytesReceived/TransferRate; 
    //Optionally use public int BytesReceived { get { return Letters.Sum(l => l.Size); } } if C# < 6, this applies to all of these
    public DateTime LastLetterReceiveDate => Letters.Max(letter => letter.EstimatedReceivedDate > DateTime.Now ? DateTime.MinValue : letter.EstimatedReceivedDate);
    public Server(string name, int transferRate, IList<Letter> letters)
    {
        Name = name;
        TransferRate = transferRate;
        Letters = letters;
    }
    public Server(string name, int transferRate, params Letter[] letters)
    {
        Name = name;
        TransferRate = transferRate;
        Letters = new List<Letter>(letters.Length);
        foreach (var letter in letters)
            Letters.Add(letter);
    }
    public static Server Deserialize(string s)
    {
        if (string.IsNullOrEmpty(s)) throw new ArgumentException("Invalid argument s: Cannot parse from null or empty string");
        var split = s.Split(FieldSeparator);
        if (split.Length != 2) throw new ArgumentException("Malformed string s! Format: Name " + FieldSeparator + "TransferRate");
        int transferRate;
        if (!int.TryParse(split[1], out transferRate)) throw new ArgumentException("Could not parse transfer rate from string: " + split[1]);
        return new Server(split[0], transferRate);
    }
    public string Serialize(Server s)
    {
        return s.ToString();
    }
    public override string ToString()
    {
        return Name + FieldSeparator + TransferRate;
    }
    public string Summary()
    {
        return Name + FieldSeparator + Letters.Count + FieldSeparator + BytesReceived + FieldSeparator + TotalTransferTime + FieldSeparator + (DateTime.Now - LastLetterReceiveDate).ToString("hh:mm:ss");
    }
}
class Program
{
    public static char EntrySeparator = ' ';
    static void Main(string[] args)
    {
        if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "servers.scv"))) throw new FileNotFoundException("Cannot find file servers.scv file at path" + Path.Combine(Environment.CurrentDirectory, "servers.scv"));
        var serversscv = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "servers.scv"));
        if (!File.Exists(Path.Combine(Environment.CurrentDirectory, "letters.csv"))) throw new FileNotFoundException("Cannot find file servers.scv file at path" + Path.Combine(Environment.CurrentDirectory, "servers.scv"));
        var letterscsv = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "servers.scv"));

        var serversSplit = serversscv.Split(EntrySeparator);
        var lettersSplit = letterscsv.Split(EntrySeparator);
        var servers = new List<Server>(serversSplit.Length);
        var letters = new List<Letter>(lettersSplit.Length);
        servers.AddRange(serversSplit.Select(Server.Deserialize));
        letters.AddRange(lettersSplit.Select(letterString => Letter.Deserialize(letterString, servers)));
        var oldServers = servers.Where(server => (DateTime.Now - server.LastLetterReceiveDate).TotalHours >= 1).Aggregate(string.Empty, (current, oldServer) => current + oldServer);
        var file = File.CreateText(Path.Combine(Environment.CurrentDirectory, "oldservers.csv"));
        file.WriteLine(oldServers); //Async possible if you're doing a continouous process (ie server does this parsing)
    }
}

现在至于其中的一些动机。

发送时间,发件人,接收者,服务器名称,信件大小

创建一个包含这些的简单类,这就是结果'Letter'。

服务器名称,速度(bits/second)

我以为你指的是字节每秒,所以我注释了一下。这个信息使类'Server'。

通过发件人发送电子邮件的时间,您可以计算电子邮件何时完全传输(发送)到服务器。如果(信件的)转帐在下一个小时内全部转帐,那么这个小时也算。

我接受了这个和你关于如何计算收到日期的解释,并制作了一个包含实际完成的转移日期的小属性。这导致'EstimatedReceivedDate'。

序列化是相当直接的,因为您几乎是自己管理的。我为您标准化了它,以便将来易于使用和扩展。还有什么……让我们来看看。是的,服务器有一个字母列表因为他们经常使用字母信息。解析过程中的信息传递是在Letter的转换方法中完成的,但也有更好的方法。一个非常可移植的方法是在Letter请求服务器时添加一个回调,然后将正确的服务器提供给它。

如果有什么不寻常的,你不明白或想要一个动机以外的以上,请随意评论。我觉得剩下的已经很明显了,不需要任何额外的背景。

我会补充一点,一些空检查是无用的,一些属性被评估的次数比它们必须的要多,所以如果你需要约束"性能",请在写问题时添加。