【问题标题】:How to generate a random number based on the time of the day?如何根据一天中的时间生成随机数?
【发布时间】:2021-08-21 12:49:57
【问题描述】:

我在 Azure IoT 中心模拟 IoT 设备(噪声传感器),下面的代码运行良好。 但是我想模拟一些更接近现实的东西,我可以在不同的时间使用不同的分贝范围。

类似这样的:

if 00.00- 7.00AM - Randum number between (10-20)
if 7am-9AM - Random number  between (20-40)
if 11.30-1.30pm Random number between 60-80

我不想创建大量的 IF、Elses,因为我想要更简洁的代码。

我应该如何以结构化的方式做到这一点?

我的代码如下:(仅相关方法)

private static async Task SendDeviceToCloudMessagesAsync(CancellationToken ct)
{
    // Initial telemetry values
    int minNoise = 20;
    int maxNoise = 90;
    var rand = new Random();
    
    while (!ct.IsCancellationRequested)
    {
        double noiseDecibels = rand.Next(minNoise, maxNoise);
                  
        // Create JSON message
        string messageBody = JsonSerializer.Serialize(
            new
            {
                eui= "58A0CB0000101DB6",
                DecibelValue = noiseDecibels
            });
        using var message = new Message(Encoding.ASCII.GetBytes(messageBody))
        {
            ContentType = "application/json",
            ContentEncoding = "utf-8",
        };
    
        // Add a custom application property to the message.
        // An IoT hub can filter on these properties without 
        // access to the message body.
        message.Properties.Add("noiseAlert", (noiseDecibels > 70) ? "true" : "false");
    
        // Send the telemetry message
        await s_deviceClient.SendEventAsync(message);
        Console.WriteLine($"{DateTime.Now} > Sending message: {messageBody}");
    
        await Task.Delay(60000);
    }
}

【问题讨论】:

  • 如果你想要有特定条件的东西,你必须有 if/else 语句来满足这个条件,不幸的是,别无选择,你可以创建一个函数来返回基于分贝值的有助于保持“清洁”的时间

标签: c# .net datetime random


【解决方案1】:

我在数据结构模式中处理这个问题(就像你问的那样),所以我会创建一个继承自 Dictionary 的 RangeHourDictionary 类。

Add 方法将添加键表示开始时间和结束时间的范围。这些值将是一个大小为 2 的 int 数组,其中第一个值表示开始范围,第二个值表示范围的结束。

另一个函数是GetRandomRange,它将获取当前时间并返回值(同样表示随机范围的开始和结束)

public class RangeDictionary : Dictionary<Range, int[]>
{
   public void Add(TimeSpan from, TimeSpan to, int[] randomValues)
   {
      Add(new Range(from, to), randomValues);
   }

   public int[] GetRandomRange(TimeSpan now)
   {
       try
       {
            return this.First(x => x.Key.From < now && x.Key.To > now).Value;
       }
       catch
       {
            return null;
       }
    }
}

public struct Range
{
     public Range(TimeSpan from, TimeSpan to) : this()
     {
          From = from;
          To = to;
      }
      public TimeSpan From { get; }
      public TimeSpan To { get; }
 }


//initialize

 var lookup = new RangeDictionary();
 lookup.Add(new TimeSpan(07, 0, 0), new TimeSpan(09, 0, 0), new int[2] { 10, 20 });
 lookup.Add(new TimeSpan(09, 30, 0), new TimeSpan(11, 0, 0), new int[2] { 40, 50 });
 lookup.Add(new TimeSpan(11, 0, 0), new TimeSpan(13, 0, 0), new int[2] { 60, 80 });


// call GetRandomRange

 var res = lookup.GetRandomRange(DateTime.Now.TimeOfDay);
 if (res != null){
    Random random = new Random();
    var randomValue = random.Next(res[0], res[1]);
 }

【讨论】:

    【解决方案2】:

    如果你有这样的特定条件,唯一的办法就是手动检查,其中哪些适用。

    private Random randomGenerator = new Random();
    
    
    
    function decibel(DateTime d) {
      int randMin = 0, randMax = 0; //the interval for the random value
      var t = d.TimeOfDay;
    
      if (t.TotalHours < 7)  //0:00 - 6:59:59 
      {
        randMin = 10; randMax = 20;
      }
      else if (d.TotalHours < 9)  //7:00 - 8:59:59 
      {
        randMin = 20; randMax = 40;
      }
      else if (d.TotalHours >= 11.5 && d.TotalHours < 13.5) //11:30 - 13:29:59
      {
        randMin = 60; randMax = 80;
      }
      ...
    
    
      // returns a rand with:  randMin <= rand < randMax
      return randomGenerator.Next(randMin, randMax);
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      相关资源
      最近更新 更多