import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
public class QueueTest {
public static void main(String[] args) {
new Bank_Simulation(480);
}
}
class Bank_Simulation {
public static final int MAX_DURATION = 30;
public static final int INTER_TIME = 5;
private int closeTime;
private List<ElementType> ev; // 事件表
private ElementType en; // 事件
private Queue<QElemType>[] listQueue; // 4个客户队列
private QElemType customer; // 客户记录
private int totalTime;
private int customerNum; // 累计客户逗留时间,客户数
public Bank_Simulation(int closeTime) { // closeTime 银行关门时间
this.closeTime = closeTime;
openForDay();
while (!this.ev.isEmpty()) {
this.en = ev.get(0);
ev.remove(0);
if (this.en.nType == 0) {
customerArrived();
} else {
customerDepartute();
}
}
System.out.println("TotalTime:"+this.totalTime+";CustomerNum:"+this.customerNum+"");
System.out.println("The Average Time is " + (float) this.totalTime
/ this.customerNum);
}
@SuppressWarnings("unchecked")
void openForDay() {
this.totalTime = 0;
this.customerNum = 0;
this.ev = new ArrayList<ElementType>();
en = new ElementType(0, 0);
ev.add(en);
this.listQueue = new LinkedList[] { null, new LinkedList<QElemType>(),
new LinkedList<QElemType>(), new LinkedList<QElemType>(),
new LinkedList<QElemType>() };
}
void customerArrived() {
this.customerNum++;
Random random = new Random();
int duration = random.nextInt(Bank_Simulation.MAX_DURATION);
int interTime = random.nextInt(Bank_Simulation.INTER_TIME);
int t = this.en.occurTime + interTime;
if (t >= this.closeTime) return;
ev.add(new ElementType(t, 0));
int i = minQueLen(listQueue);
enQueue(this.listQueue[i], new QElemType(this.en.occurTime, duration));
if (this.listQueue[i].size() == 1)
this.ev.add(new ElementType(this.en.occurTime + duration, i));
}
void customerDepartute() {
int i = this.en.nType;
this.customer = this.listQueue[i].poll();
this.totalTime += this.en.occurTime - this.customer.arrivalTime;
if (!this.listQueue[i].isEmpty()) {
this.ev.add(new ElementType(this.en.occurTime
+ this.listQueue[i].peek().duration, i));
}
}
/***
* 求4个队列中最短队列
*
* @param q
* @return
*/
int minQueLen(Queue<QElemType>[] q) {
int minlen = q[1].size();
for (int i = 1, len = 5; i < len; i++) {
int temp = q[i].size();
if (minlen > temp)
minlen = temp;
}
return minlen < 1 ? 1 : minlen;
}
void enQueue(Queue<QElemType> queue, QElemType e) {
queue.add(e);
}
int compare(ElementType a, ElementType b) {
int t = a.occurTime - b.occurTime;
if (t < 0)
return -1;
else if (t == 0)
return 0;
else
return 1;
}
}
class ElementType {
public int occurTime;
public int nType;
public ElementType(int occurTime, int nType) {
super();
this.occurTime = occurTime;
this.nType = nType;
}
}
class QElemType {
public int arrivalTime;
public int duration;
public QElemType(int arrivalTime, int duration) {
super();
this.arrivalTime = arrivalTime;
this.duration = duration;
}
}
console:
TotalTime:354650;CustomerNum:238
The Average Time is 1490.1261