根据到达和离开时间矩阵计算出给定时间内队列中的人数?

时间:2017-10-31 20:45:22

标签: python algorithm time-series simulation

我一直在考虑如何在数小时内完成这项工作,但我被卡住了。

我有一个矩阵A,有客户的到达时间,矩阵D,有客户的出发时间。例如。到达矩阵中的时间意味着一个客户到达那个时间,并且离开矩阵中的时间意味着一个客户离开。

我试图以1 = 1的间隔从t = 1..800绘制商店中客户数量的时间序列。但是,客户的到达和离开时间由随机变量确定,这是随着时间步长以随机间隔增加而运行的模拟,因此我发现很难在模拟本身中以给定的时间间隔存储客户数量。

我认为必须有一种方法可以在给定到达和离开时间矩阵的情况下以均匀间隔的时间间隔填写客户数量的矩阵N,但我不能为我的生活想想它是什么。有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

到达和离开是"事件",您的数组包含这些事件的时间。基本逻辑是查找下一个事件的时间并执行与该事件相关的更新。对于到达,队列长度增加。对于离开,队列长度递减。以下是一个相当暴力的实现(Python3,因为你没有指定),这个想法会在它改变时打印出时间和队列长度:

a = [1.1, 2.9, 5.1, 6.5]
d = [3.5, 5.2, 7.2, 8.0]

queue = 0
a_index = 0
d_index = 0
print(0, ':', queue)

while a_index < len(a) and d_index < len(d):
    if a[a_index] < d[d_index]:  # did an arrival come first?
        queue += 1
        print(a[a_index], ':', queue)
        a_index += 1
    else:
        queue -= 1
        print(d[d_index], ':', queue)
        d_index += 1

# ran out of elements in one of the arrays,
# iterate through remainder of the other

while a_index < len(a):
    queue += 1
    print(a[a_index], ':', queue)
    a_index += 1

while d_index < len(d):
    queue -= 1
    print(d[d_index], ':', queue)
    d_index += 1

如果您只想在整数时间打印,请将它们设置为事件:

a = [1.1, 2.9, 5.1, 6.5]
d = [3.5, 5.2, 7.2, 8.0]

queue = 0
a_index = 0
d_index = 0
print_time = 1
max_time = 10
print(0, ':', queue)

while a_index < len(a) and d_index < len(d):
    if a[a_index] < d[d_index] and a[a_index] <= print_time:
        queue += 1
        a_index += 1
    elif d[d_index] <= print_time:
        queue -= 1
        d_index += 1
    else:
        print(print_time, ':', queue)
        print_time += 1

while a_index < len(a):
    if a[a_index] <= print_time:
        queue += 1
        a_index += 1
    else:
        print(print_time, ':', queue)
        print_time += 1

while d_index < len(d):
    if d[d_index] <= print_time:
        queue -= 1
        d_index += 1
    else:
        print(print_time, ':', queue)
        print_time += 1

while print_time <= max_time:
    print(print_time, ':', queue)
    print_time += 1

这些无疑可以收紧,但他们传达了这种方法。

如果你有超过这么少的事件,更好的组织原则是将事件放在优先级队列中,按发生时间排序,然后逐个拉出它们并调度到适当的状态基于发生的事件类型的转换逻辑。您可以在this paper中找到此方法的逻辑。本文使用Java实现了这些思想,但是可以使用Python3实现和演示排队模型here