我有一个任务,我坚持它[类,数组,周期]

时间:2015-09-23 18:38:44

标签: c#

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

*

电子邮件和服务器之间的转移正在发生。通过互联网的接口速度可从文件中获知。您需要列出一个服务器列表,这些服务器在至少一个小时内没有任何数据。通过让发件人发送电子邮件的时间,您可以计算电子邮件何时完全传输(发送)到服务器。如果转移(信件)在下一个小时完全转移,那么这个小时也是重要的。 letters.csv(发送信件的时间,发件人,收件人,服务器的名称,字母大小)servers.csv(服务器的名称,速度(咬/秒))所有结果都有放在.csv文件中。结果应按以下顺序写出:服务器名称,收到的信件,所有信件的总体大小,转移所有信件需要多长时间,服务器没有收到任何信件的时间。所有信件都在收到的同一时间发送。应该没有服务器女巫至少没有使用过一次。

*

letters.csv例子

  

13:15:47; Gustas@inbox.lt; Justas@inbox.lt; Serveris_1; 50   05:45:11; Tomas@inbox.lt; Simas@inbox.lt; Serveris_3; 42   12:13:22; Mindaugas@inbox.lt; Justas@inbox.lt; Serveris_3; 6   07:15:42; Gustas@inbox.lt; Mindaugas@inbox.lt; Serveris_2; 19   08:18:32; Jonas@inbox.lt; Tomas@inbox.lt; Serveris_1; 112

servers.scv示例

  

Serveris_1; 15   Serveris_2; 24   Serveris_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; 
        }
    }
}

我甚至不知道我是否正确行事。我不知道怎么做计数部分。我希望我把这个任务理解得可以理解。希望你们中的任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

我提供的答案与您的示例的长度相符。它是彻底的,并且为您提供了很好的证据,因为您提供了很好的证明。我将激励源代码区域以下的一些决策。一切都应该包括在内。

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)
    }
}

至于其中一些动机。

  

发送信件的时间,发件人,收件人,服务器的名称,字母大小

制作一个包含这些内容的简单课程,即结果&#39; Letter&#39;。

  

服务器的名称,速度(咬/秒)

我认为你的意思是每秒字节数,所以我评论说。此信息使课程“服务器”#。

  

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

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

序列化非常简单,因为你自己管理的很多。我为你标准化,以便将来使用和扩展。还有什么......让我们看看。是的,服务器有一个字母列表,因为它们经常使用字母信息。解析期间的信息传输是在Letter的转换方法中完成的,但也有更好的方法。一个非常便携的方法是在它要求服务器时从Letter中添加一个回调,然后再将正确的服务器提供给它。

如果有任何不寻常的事情你不理解或想要除上述之外的动机,请随时发表评论。我觉得其余部分相当明显,并且不需要任何额外的背景。

我将补充一点,一些空检查是无用的,并且如果你需要约束&#39; performant&#39;那么一些属性的评估次数比它们要多得多。请在撰写问题时添加。这不是低效的,但它没有得到优化。