-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation.go
96 lines (83 loc) · 1.85 KB
/
simulation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"math/rand"
"time"
)
// Car the main object that is moved through a lane
type Car struct {
id string
speed float64
lanePos int
lane *Lane
}
func (car *Car) String() string {
return car.id
}
// SimulationConfig is the config that is used in a simulation
type SimulationConfig struct {
sizeOfLane int
}
// Simulation handles the channel to get updates from and the configuration
type Simulation struct {
drawUpdateChan chan bool
runningSimulation bool
config SimulationConfig
cancelSimulation chan bool
}
func (singleSim *Simulation) close() {
singleSim.runningSimulation = false
}
// Lane holds a list of locations
type Lane struct {
Locations []Location
sizeOfLane int
}
// Location is one spot on a lane
type Location struct {
Cars map[string]*Car // Allows for easy removal of the car
}
func moveCarsThroughBins(lane *Lane, movementChan chan *Lane, start bool) {
var location Location
if start {
location = (lane.Locations)[0]
} else {
location = lane.Locations[len(lane.Locations)-2]
}
for {
movementTime := rand.ExpFloat64()
select {
case <-time.After(time.Duration(movementTime) * time.Second):
movementChan <- lane
break
default:
if start && len(location.Cars) == 0 {
return
}
}
}
}
// MoveCarInLane moves the car through a lane using an exponential clock and probability of movement
func MoveCarInLane(car *Car, movementChan chan *Car) {
p := 0.5
movementTime := rand.ExpFloat64() / car.speed
select {
case <-time.After(time.Duration(movementTime) * time.Second):
if UniformRand() < p {
movementChan <- car
return
}
go MoveCarInLane(car, movementChan)
}
}
//
func getCarFromLocation(location *Location, del bool) (*Car) {
var currCar *Car
for k, v := range location.Cars {
if del {
delete(location.Cars, k)
}
currCar = v
break
}
return currCar
}