-
Notifications
You must be signed in to change notification settings - Fork 0
/
professor.r
executable file
·154 lines (105 loc) · 2.48 KB
/
professor.r
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/Rscript
# Professor & Rain
# Program inspired by example from book "Teach Yourself Scheme in Fixnum Days"
# Professor walks between work and home
# Initially, he has 1 umbrella in each location
# When it rains he takes his umbrella to other location
# After how many walks will he find himself in location without umbrella when it rains?
# -----------------------------------
rain_probability <- 0.4
max_walks <- 500
loud <- FALSE
# Location is vector with number of umbrellas and professor position
home <- c(1,1)
work <- c(1,0)
# -----------------------------------
random <- function() {
return(runif(1))
}
atHome <- function() {
return(1 == home[2])
}
goHome <- function(umb=FALSE) {
if(loud) { print("Go home") }
mu(umb,1,-1) ; pos(1,0)
}
goToWork <- function(umb=FALSE) {
if(loud) { print("Go to work") }
mu(umb,-1,1) ; pos(0,1)
}
# Set professor position
pos <- function (h,w) {
home[2] <<- h ; work[2] <<- w
}
# Move umbrella
mu <- function(u,h,w) {
if (u) {
home[1] <<- home[1] + h
work[1] <<- work[1] + w
}
}
goHomeWithUmbrella <- function() {
goHome(TRUE)
}
goToWorkWithUmbrella <- function() {
goToWork(TRUE)
}
goWithoutUmbrella <- function() {
if (atHome()) goToWork() else goHome()
}
goWithUmbrella <- function() {
if (atHome()) {
if (umbrellaAt(home)) {
goToWorkWithUmbrella()
return(TRUE)
}
} else {
if (umbrellaAt(work)) {
goHomeWithUmbrella()
return(TRUE)
}
}
return(FALSE)
}
umbrellaAt <- function(location) {
return(1 <= location[1])
}
raining <- function() {
return(random() < rain_probability)
}
go <- function() {
for (walks in 0:max_walks) {
if (raining()) {
if(loud) { print("Raining") }
if(!goWithUmbrella()){ return(walks) }
} else {
if(loud) { print("Not raining") }
goWithoutUmbrella()
}
if(loud) { print(home) ; print(work) }
}
return(walks)
}
resetLocations <- function() {
home <<- c(1,1) ; work <<- c(1,0)
}
display <- function (t,n) {
print(sprintf("%s%0.3f", t, n))
}
# -----------------------------------
main <- function() {
trials <- 2000
results <- vector(mode = "integer",length = trials)
for (i in 1:trials) {
resetLocations()
results[i] <- go()
}
display("Mean: ", mean(results))
display("Median: ", median (results))
display("Standard deviation: ", sd(results))
hist(results)
boxplot(results)
}
# -----------------------------------
main()
# -----------------------------------