初学者定时器线程程序来回答谜语

Beginner Timer Threaded Program to Answer a Riddle

所以我试图通过编写一个程序来解决我朋友在求职面试中遇到的问题:"At the two second time mark, a mosquito starts spawning another mosquito every second at the mark and thereafter. Starting with one mosquito at t = 0s, how many mosquitoes will we have after 8.5 seconds?"

public class ok
    {
        public static int num;

        public static void mosquito()
        {
            Task.Delay(1000);
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += OnTimedEvent;
            aTimer.Interval = 1000;
            aTimer.Enabled = true;
        }

        // Specify what you want to happen when the Elapsed event is raised.
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            num++;
            ThreadStart mos = mosquito;

        }
    }

public static void Main()
        {
            ok.mosquito();
            SendWithDelay();

            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }

        // Prints mosquito count after 8.5 seconds
        private static async Task SendWithDelay()
        {
            await Task.Delay(8500);
            Console.WriteLine(ok.num);
        }

这是我尝试编写的简单代码,但显然失败得很惨。我尝试阅读任务 API 并以更好的方式理解发生了什么,我知道我需要确保访问变量 "num",它跟踪蚊子数量是线程安全,但我对此很生疏。

非常感谢您的帮助。谢谢!

这是一个简单的离散 2^n 算法。

2s mark we have 1 + 1 = 2
3s mark we have 1 + 1 + 2 = 4
4s mark we have 1 + 1 + 2 + 4 = 8
5s mark we have 1 + 1 + 2 + 4 + 8 = 16

等等

代码示例

var numMosqito = 1;
for (float time = 0; time  <= 8.5; time ++)
{
     if (time  >= 2)
         numMosqito += numMosqito;


     Console.WriteLine("{0}, {1}", time, numMosqito);
}

Console.ReadLine();

把问题翻过来,两秒前的所有蚊子都会产生另一只蚊子,所以我们需要一点历史,让我们使用一个数组:

int[9] mosquitoHistory;

从计时器开始会使事情变得复杂,假设事情每秒发生一次,让我们使用循环。

for (i = 0, i++, i < 9)
{

如果我们能得到2s前的蚊子数量

int matureMosquitos = (seconds-2 >= 0 ? mosquitoHistory[seconds-2] : 0);

写下这一秒的蚊子数量,即我们上一秒的数量加上成熟蚊子产生的数量。

mosquitoHistory[seconds] = (seconds-1 >= 0 ? mosquitoHistory[seconds-1] : 1) + matureMosquitos;

并输出结果

Console.WriteLine(mosquitoHistory[seconds]); 

最后,如果你想让它模拟,请稍等片刻:

Threading.Thread.Sleep(1000);

把它们放在一起,这就是你得到的。

using System;
public class Program
{
    public static void Main()
    {
        int[] mosquitoHistory = new int[9];
        for (int seconds = 0; seconds < 9; seconds++)
        {
            int matureMosquitos = (seconds-2 >= 0 ? mosquitoHistory[seconds-2] : 0);
            mosquitoHistory[seconds] = (seconds-1 >= 0 ? mosquitoHistory[seconds-1] : 1) + matureMosquitos;                 
            Console.WriteLine(mosquitoHistory[seconds]); 
            Threading.Thread.Sleep(1000);
        }
    }
}

我得到了 34 只蚊子。