##################################################################
#
#  Setup: a patent office. Incoming jobs arrive randomly,
#         with Poisson distribution of parameter Lambda.
#         Five clercks can process one job per day, or a
#         total of 5 (Service.per.Day). Those which cannot
#         be completed the day of their arrival, are queued
#         for the following day(s).
#
#         We simulate what happens for different combinations
#         of arrival rates (Lambda) and capacity of the office
#         (Service.per.Day), over a period od days (Days).
#         In particular, we want to look at the number of
#         pendings jobs at the end of each day and the
#         probability of a job  not being serviced the day of its
#         arrival
#
#         Notice that you want to have everything neatly parameterized
#         at the start, so if you decide to change, e.g. the number of
#         days over which you want to run the simulation, you only have
#         to change one line.
#
##################################################################

Pending          <- 0           # Initially, no pending jobs.
Service.per.Day  <- 5           # Capacity of the office
Lambda           <- 4.5         # Mean of the number of random,
                                # Poisson-distributed arrivals per day.
Days             <- 200         # Days over which the simulation extends.
Journal          <- rep(0,Days) # Vector to store pending jobs at the end
                                # of each day.

##  SIMULATION BEGINS ##

for ( i in 1:Days ) {
  Arrivals   <- rpois(n=1, lambda=Lambda)
  Pending    <- max(Pending + Arrivals - Service.per.Day, 0)
  Journal[i] <- Pending
}

hist(Journal)                   # See approx. distribution jobs pending at
                                # the end of each day.

plot(Journal, type="l",         # Pending jobs at the end of each day.
     xlab="Day", ylab="Pending",
     main="Jobs at the end of each day")

sum(Journal > 0) / Days         # The fraction of days when we were not able
                                # to process the full workload.
