# CSC 121, Jan-Apr 2017, Large Assignment #1, Function definitions # Function for simulating the queue of people waiting to be served. simulate_queue <- function (open_time, rate, low, high) { # Check validity of arguments (not required by assignment handout). stopifnot (open_time >= 0) stopifnot (rate > 0) stopifnot (low >= 0 && high >= low) # Initialize the variables that will hold the results to be empty. arrival_times <- numeric(0) departure_times <- numeric(0) queue_lengths <- numeric(0) # Set the time and the number of customers in the queue to 0 at the start. time <- 0 queue <- 0 # Initialize the times for next events - next arrival time, and next # completion of service (Inf when there is no customer being served). next_arrival_time <- arrival_interval(rate) next_departure_time <- Inf # Main loop, continues as long as there are still events that will happen. while (next_arrival_time < open_time || next_departure_time < Inf) { # Check whether the next event will be an arrival or departure, # and then handle it. if (next_arrival_time < open_time && next_arrival_time < next_departure_time) { # Process the event of a customer arriving. time <- next_arrival_time arrival_times <- c(arrival_times,time) queue_lengths <- c(queue_lengths,queue) next_arrival_time <- time + arrival_interval(rate) if (queue == 0) next_departure_time <- time + service_interval(low,high) queue <- queue + 1 } else { # Process the event of a customer departing (after finishing # servicing them). time <- next_departure_time departure_times <- c(departure_times,time) queue <- queue - 1 if (queue == 0) next_departure_time <- Inf else next_departure_time <- time + service_interval(low,high) } } # Return the vectors recording what happened. list (arrival_times = arrival_times, queue_lengths = queue_lengths, departure_times = departure_times) } # Functions that randomly generate the time to the next arrival and # the time to when the customer who has started being served is done. arrival_interval <- function (rate) rexp(1,rate) service_interval <- function (low, high) runif(1,low,high) # Function to run multiple simulations with different random seeds. run_simulations <- function (seeds, open_time, rate, low, high) { # Create vectors that will hold the results of the simulations. served <- numeric(length(seeds)) maxqueue <- numeric(length(seeds)) avewait <- numeric(length(seeds)) overtime <- numeric(length(seeds)) # Do all the simulations, recording the results in the above variables. for (i in 1:length(seeds)) { set.seed(seeds[i]) r <- simulate_queue(open_time,rate,low,high) served[i] <- length(r$arrival_times) maxqueue[i] <- max(r$queue_lengths) avewait[i] <- mean(r$departure_times-r$arrival_times) overtime[i] <- max (0, r$departure_times[length(r$departure_times)]-open_time) } # Return the results as a data frame. data.frame (seed=seeds, open_time, rate, low, high, served, maxqueue, avewait, overtime) }