想象一下,我在队列中有一个等待列表的等待列表
Service 1 - 5 minutes
Service 2 - 10 minutes
Service 3 - 5 minutes
Service 4 - 15 minutes
Service 5 - 20 minutes
如果我有两名工作人员为队列中的这五个客户提供服务,我怎么能估计下一个人在商店里走路的等待时间。
答案 0 :(得分:6)
实际上它非常简单 - 它是"W" queue model as described by Eric Lippert。
设置一个阵列两个“工作人员”成员:
List<int>[] staff = new [] {new List<int>(), new List<int>()};
定义你的队列:
int[] queue = new int[] {5, 10, 5, 15, 20};
然后模拟处理 - 每个后续客户将转到首先完成的服务商:
foreach (int i in queue)
{
List<int> shortest = staff.OrderBy(s=>s.Sum()).First();
shortest.Add(i);
}
“下一个”进入的人必须等到第一个服务商免费,这是每个服务客户的总和:
int nextTime = staff.Min(s=>s.Sum());
Console.WriteLine("The wait time for the next customer is {0} minutes",nextTime);
输出:
下一位客户的等待时间为25分钟。
答案 1 :(得分:1)
这是一种不那么优雅的方式......
private static int GetEstimatedWaitTime(Queue<int> currentQueue, int numServers)
{
int waitTime = 0;
// Short-circuit if there are more servers than items in the queue
if (currentQueue.Count < numServers) return waitTime;
// Create a copy of the queue so we can dequeue from it
var remainingItems = new Queue<int>();
foreach (var item in currentQueue)
{
remainingItems.Enqueue(item);
}
// Grab an item for each server
var itemsBeingServiced = new List<int>();
for (int i = 0; i < numServers; i++)
{
itemsBeingServiced.Add(remainingItems.Dequeue());
}
do
{
// Get the shortest item left, increment our wait time, and adjust other items
itemsBeingServiced.Sort();
var shortestItem = itemsBeingServiced.First();
waitTime += shortestItem;
itemsBeingServiced.RemoveAll(item => item == shortestItem);
for (int i = 0; i < itemsBeingServiced.Count; i++)
{
itemsBeingServiced[i] = itemsBeingServiced[i] - shortestItem;
}
// Add more items for available servers if there are any
while (itemsBeingServiced.Count < numServers && remainingItems.Any())
{
itemsBeingServiced.Add(remainingItems.Dequeue());
}
} while (itemsBeingServiced.Count >= numServers);
return waitTime;
}