This first snippet is comprised of the following functionality:
- **Entity Class**: Represents entities in the simulation, which will hold individual properties.
- **Event Class**: Represents different events that can occur in the simulation.
- **Simulation Class**: Manages the overall simulation, including scheduling and executing events.
- **Statistics Class**: Collects and reports simulation statistics.
- **Main Function**: Where the simulation is configured and started.
- We have a **Service event** to indicate when an entity is being serviced.
- We track both the arrival and departure times of entities.
- The `Statistics` class computes and reports the average wait time of all entities at the end of the simulation.
- We use a `main` function to initiate the simulation and report statistics.
# Source Code Snippet:
class Entity {
constructor(id, arrivalTime) {
this.id = id;
this.arrivalTime = arrivalTime;
this.departureTime = null;
}
}
class Event {
constructor(time, type, entity) {
this.time = time;
this.type = type;
this.entity = entity;
}
}
class Simulation {
constructor() {
this.currentTime = 0;
this.eventQueue = [];
this.entities = [];
}
schedule(event) {
this.eventQueue.push(event);
this.eventQueue.sort((a, b) => a.time - b.time);
}
run() {
while (this.eventQueue.length > 0) {
let event = this.eventQueue.shift();
this.currentTime = event.time;
if (event.type === 'ARRIVAL') {
console.log(`Entity ${event.entity.id} arrived at time ${this.currentTime}`);
this.entities.push(event.entity);
// Schedule next arrival event
this.schedule(new Event(this.currentTime + Math.random() * 10, 'ARRIVAL', new Entity(this.entities.length, this.currentTime)));
// Schedule a service event
this.schedule(new Event(this.currentTime + Math.random() * 5, 'SERVICE', event.entity));
}
else if (event.type === 'SERVICE') {
console.log(`Entity ${event.entity.id} is being serviced at time ${this.currentTime}`);
// Schedule a departure event
this.schedule(new Event(this.currentTime + Math.random() * 5, 'DEPARTURE', event.entity));
}
else if (event.type === 'DEPARTURE') {
console.log(`Entity ${event.entity.id} departed at time ${this.currentTime}`);
event.entity.departureTime = this.currentTime;
}
}
}
}
class Statistics {
static report(entities) {
let totalWaitTime = entities.reduce((sum, entity) => sum + (entity.departureTime - entity.arrivalTime), 0);
let averageWaitTime = totalWaitTime / entities.length;
console.log(`Average wait time: ${averageWaitTime}`);
}
}
function main() {
let simulation = new Simulation();
// Schedule the first arrival event to kickstart the simulation
simulation.schedule(new Event(Math.random() * 10, 'ARRIVAL', new Entity(0, 0)));
simulation.run();
// Generate report
Statistics.report(simulation.entities);
}
main();