Skip to content

Instantly share code, notes, and snippets.

@xixixao
Created December 4, 2013 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xixixao/7791421 to your computer and use it in GitHub Desktop.
Save xixixao/7791421 to your computer and use it in GitHub Desktop.
http://michalsrb.me/teatable/ Run like: > (new Simulation (ExponentialSampler 2), (ConstantSampler 2)).run 100
# http://michalsrb.me/teatable/
#
# (new Simulation (ExponentialSampler 2), (ConstantSampler 2)).run 100
class Simulation
constructor: (@interArrival, @serviceTime) ->
@events = []
@t = 0
@population = 0
@scheduleArrival()
@capacity = 20
arrival: =>
@population++
if @population < @capacity
@scheduleArrival()
if @population is 1
@scheduleCompletion()
scheduleArrival: ->
t = @interArrival.sample()
@scheduleEvent t, @arrival
completion: =>
@population--
if @population > 0
@scheduleCompletion()
if @population is @capacity - 1
@scheduleArrival()
scheduleCompletion: ->
t = @serviceTime.sample()
@scheduleEvent t, @completion
scheduleEvent: (t, cb)->
@events.push [@t + t, cb]
run: (duration) ->
@events = @events.sort ([t1], [t2]) -> t2 - t1
[t, cb] = @events.shift()
@t += t
cb()
log @population, @events.length
@run duration - 1 if duration
ConstantSampler = (c) ->
sample: ->
c
UniformSampler = (a, b) ->
sample: ->
(b - a) * Math.random() + a
ExponentialSampler = (λ) ->
sample: ->
- (Math.log Math.random()) / λ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment