所以我有一个问题,我已经绞尽脑汁思考了大约一周了。情况是:
Consider a checkout line at the grocery store. During any given second, the probability that a new customer joins the line is 0.02 (no more than one customer joins the line during any given second). The checkout clerk takes a random amount of time between 20 seconds to 75 seconds to serve each customer. Write a program to simulate this scenario for about ten million seconds and print out the average number of seconds that a customer spends waiting in line before the clerk begins to serve the customer. Note that since you do not know the maximum number of customers that may be in line at any given time, you should use an ArrayList and not an array.
预计平均等待时间应在 500 到 600 秒之间。然而,我还没有得到接近这个范围的答案。鉴于新顾客排队的概率仅为 2%,我预计排队人数不会超过 1 人,因此平均等待时间约为 45-50 秒。我问过一位 friend (数学专业)对这个问题的看法,他同意在 2% 的概率下,45 秒是一个合理的平均值。到目前为止我的代码是:
package grocerystore;
import java.util.ArrayList;
import java.util.Random;
public class GroceryStore {
private static ArrayList<Integer> line = new ArrayList();
private static Random r = new Random();
public static void addCustomer() {
int timeToServe = r.nextInt(56) + 20;
line.add(timeToServe);
}
public static void removeCustomer() {
line.remove(0);
}
public static int sum(ArrayList<Integer> a) {
int sum = 0;
for (int i = 0; i < a.size(); i++) {
sum += a.get(i);
}
return sum;
}
public static void main(String[] args) {
int waitTime = 0;
int duration = 10000;
for (int i = 0; i < duration; i++) {
double newCust = r.nextDouble();
if (newCust < .02) {
addCustomer();
}
try {
for (int j = 0; j < line.get(0); j++) {
waitTime = waitTime + sum(line);
}
} catch (IndexOutOfBoundsException e) {}
if (line.isEmpty()) {}
else {
removeCustomer();
}
}
System.out.println(waitTime/duration);
}
}
任何有关此问题的建议将不胜感激。
最佳答案
这里有一些伪代码可以帮助您进行计划
for each second that goes by:
generate probability
if probability <= 0.02
add customer
if wait time is 0
if line is not empty
remove customer
generate a new wait time
else
decrement wait time
关于java - 使用 Java 模拟杂货店排队队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843937/