(Section 4.4)
Suppose that as they walk along the Yellow Brick Road, our Oz friends come upon a meadow that has flowers of the following colors:
The friends decide to wander through this meadow picking flowers.
Write a function that makes each person take turns wandering through the field until he/she has collected the desired number of his/her desired flowers.
The function should return the total number of flowers collected by everyone.
As it runs, the function should report what flowers each person collects.
Nested loops: loop within a loop.
Simplify the problem, at first:
Write a function that does the required work for just one person.
walk_meadow <- function(person, color, wanted, report = FALSE) {
picking <- TRUE
pick_count <- 0
desired_count <- 0
if (report) {
cat(person, " picks flowers of the following colors: ")
}
while (picking) {
picked <- sample(flower_colors, size = 1)
pick_count <- pick_count + 1
if (picked == color) desired_count <- desired_count + 1
if (desired_count == wanted) picking <- FALSE
if (report) {
message <- ifelse(
picking,
paste(picked, ", ", sep = ""),
paste(picked, ".\n\n", sep = "")
)
cat(message)
}
}
pick_count
}
Let’s try it on the Quadling Boq:
Boq picks flowers of the following colors: crimson, crimson, blue, blue, crimson, red, blue.
[1] 7
Dorothy picks flowers of the following colors: orange, red, red, orange, red, pink, red, orange, crimson, red, crimson, crimson, red, crimson, orange, crimson, crimson, pink, red, red, pink, orange, crimson, orange, orange, red, orange, blue, pink, orange, blue, orange, pink, blue.
Tin Man picks flowers of the following colors: orange, pink, red, red.
Scarecrow picks flowers of the following colors: blue, pink, red, blue.
Lion picks flowers of the following colors: orange, orange, red, orange, crimson, pink, crimson, crimson, red, red, blue, blue, crimson, red, red, red, blue, crimson.
Toto picks flowers of the following colors: blue, blue, crimson, red, red, orange, orange, crimson, crimson, crimson, orange, crimson, blue, orange, blue, crimson, crimson, pink.
[1] 78
If you don’t need the reports, set report
to FALSE
: