Two guys meet

Two guys meet

If two guys meet, there is standard verbiage, but some uncertainty in how long they need to greet and respond. We can simulate this as an introductory example.

We call the needed modules and define some types and data:

using Simulate, Printf

struct Guy
    name
end

abstract type Encounter end
struct Meet <: Encounter
    someone
end
struct Greet <: Encounter
    num
    from
end
struct Response <: Encounter
    num
    from
end

comm = ("Nice to meet you!", "How are you?", "Have a nice day!", "bye bye")

We implement the behavior of the "guys" as step!-functions of a state machine.

say(name, n) =  @printf("%5.2f s, %s: %s\n", tau(), name, comm[n])

function step!(me::Guy, ฯƒ::Meet)
    event!(๐ถ, SF(step!, ฯƒ.someone, Greet(1, me)), after, 2*rand())
    say(me.name, 1)
end

function step!(me::Guy, ฯƒ::Greet)
    if ฯƒ.num < 3
        event!(๐ถ, SF(step!, ฯƒ.from, Response(ฯƒ.num, me)), after, 2*rand())
        say(me.name, ฯƒ.num)
    else
        say(me.name, 4)
    end
end

function step!(me::Guy, ฯƒ::Response)
    event!(๐ถ, SF(step!, ฯƒ.from, Greet(ฯƒ.num+1, me)), after, 2*rand())
    say(me.name, ฯƒ.num+1)
end

Then we define some "guys" and a starting event and tell the clock ๐ถ to run for twenty "seconds":

foo = Guy("Foo")
bar = Guy("Bar")

event!(๐ถ, SF(step!, foo, Meet(bar)), at, 10*rand())
run!(๐ถ, 20)

If we source this code, it will run a simulation:

julia> include("docs/examples/greeting.jl")
 7.30 s, Foo: Nice to meet you!
 8.00 s, Bar: Nice to meet you!
 9.15 s, Foo: How are you?
10.31 s, Bar: How are you?
11.55 s, Foo: Have a nice day!
12.79 s, Bar: bye bye
Finished: 6 events, simulation time: 20.0

Then we reset the clock ๐ถ for further simulations.

julia> reset!(๐ถ)
clock reset to tโ‚€=0, sampling rate ฮ”t=0.

See also: tau, ๐ถ, SF, event!, run!, reset!