我有一种方法来计算队列中的等待时间。它在很小的范围内都能正常工作。但是,您很快就会发现,在很大范围内执行此操作将变得非常乏味。在此示例中,如果您在队列中排名第一,则等待时间为“很快”。如果大于1且小于5:0到1周,依此类推...我如何遍历此列表以动态查找队列中的位置?
if ((PlaceInQueue) <= 1)
{
result = "Very soon!";
}
if ((PlaceInQueue) > 1 & (PlaceInQueue) < 5)
{
result = "From 0 to 1 weeks.";
}
if ((PlaceInQueue) >= 5 & (PlaceInQueue) < 11)
{
result = "From 1 to 2 weeks.";
}
if ((PlaceInQueue) >= 11 & (PlaceInQueue) < 17)
{
result = "From 2 to 3 weeks.";
}
if ((PlaceInQueue) >= 17 & (PlaceInQueue) < 23)
{
result = "From 3 to 4 weeks.";
}
这就是我已经开始并且想要完成的事情。在while循环之前的前几条if语句可能需要进行硬编码,因为数学并不精确,而其余的将是动态的。因此,在此示例中,结果一直是正确的,直到队列中的位置等于或大于11(在while循环内)。
int n = 1;
int max = 300; // Stop calculating when the max is reached
var PlaceInQue = (Convert.ToInt32(placeInQueue)); // This is the position in the Que
foreach (var item in PlaceInQue)
{
if (PlaceInQue <= 1)
{
result = "Very soon!";
}
if (PlaceInQue > 1 & PlaceInQue < 5)
{
result = "From 0 to 1 weeks.";
}
if (PlaceInQue >= 5 & PlaceInQue < 11)
{
result = "From 1 to 2 weeks.";
}
while (n < max)
{
if (PlaceInQue >= (should increment from 11 and then 17 then 23 then 29 and so on...) & PlaceInQue < (increment from 17 then 23 then 29 then 35 and so on...)
{
result = (should increment from "2 to 3 weeks" and then "3 to 4 weeks" and so on until max is reached...)
}
n++;
}
}
答案 0 :(得分:1)
我认为您需要这样的东西:
if (PlaceInQue <= 1)
{
result = "Very soon!";
}
else if (PlaceInQue < 5)
{
result = "From 0 to 1 weeks.";
}
else if (PlaceInQue < 11)
{
result = "From 1 to 2 weeks.";
}
else if
{
for (int n = 11; n <= max; n += 5)
{
if (PlaceInQue >= n && PlaceInQue < n + 5)
{
int weeks = n / 5;
result = $"From {weeks} to {(weeks + 1)} weeks.";
break;
}
}
}
答案 1 :(得分:0)
下面的代码对我有用,我已经检查了可能的边缘情况。让我知道它是否对您不起作用。
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Queue<int> queue = new Queue<int>(Enumerable.Range(1, 300));
foreach (var placeInQueue in queue)
{
if(placeInQueue <= 1)
Console.WriteLine($"Place: {placeInQueue}. Very soon!");
else if(placeInQueue < 300)
{
var fromTo = GetFromTo(placeInQueue);
Console.WriteLine($"Place: {placeInQueue}. From {fromTo.Item1} to {fromTo.Item2} weeks.");
}
}
}
private static Tuple<int,int> GetFromTo(int place)
{
if (place < 5)
return new Tuple<int, int>(0, 1);
var q1 = place / 5;
var q2 = 0;
if((place + 1) % 6 == 0)
{
q2 = (place + 1) / 6;
q1 = int.MaxValue;
}
else
q2 = (place/6) == 0 ? q1 : (place/6);
var from = Math.Min(q1, q2);
var to = from + 1;
return new Tuple<int, int>(from, to);
}
}