First we set up the chocolate randomisation process:
chocolate_types<-c("Cherry Ripe","Dairy Milk","Crunchie", "Caramello","Flake")
make_pack<-function(){
sample(chocolate_types, 8, replace=TRUE)
}
make_pack()
## [1] "Caramello" "Crunchie" "Dairy Milk" "Caramello" "Crunchie"
## [6] "Flake" "Dairy Milk" "Crunchie"
make_pack()
## [1] "Caramello" "Dairy Milk" "Crunchie" "Dairy Milk" "Caramello"
## [6] "Flake" "Caramello" "Flake"
replicate(5, make_pack())
## [,1] [,2] [,3] [,4] [,5]
## [1,] "Cherry Ripe" "Crunchie" "Caramello" "Caramello" "Crunchie"
## [2,] "Cherry Ripe" "Caramello" "Cherry Ripe" "Cherry Ripe" "Caramello"
## [3,] "Crunchie" "Crunchie" "Caramello" "Crunchie" "Dairy Milk"
## [4,] "Caramello" "Dairy Milk" "Flake" "Flake" "Cherry Ripe"
## [5,] "Dairy Milk" "Flake" "Crunchie" "Dairy Milk" "Flake"
## [6,] "Flake" "Flake" "Cherry Ripe" "Crunchie" "Crunchie"
## [7,] "Crunchie" "Flake" "Cherry Ripe" "Flake" "Flake"
## [8,] "Crunchie" "Cherry Ripe" "Caramello" "Flake" "Dairy Milk"
Now, we need to work out which bar we have the most of, and count them
count_most<-function(a_pack){
count <- table(a_pack)
most <- which.max(count)
count[most]
}
a_test_pack<-make_pack()
a_test_pack
## [1] "Cherry Ripe" "Dairy Milk" "Flake" "Crunchie" "Flake"
## [6] "Flake" "Caramello" "Dairy Milk"
count_most(a_test_pack)
## Flake
## 3
We’re going to do this lots of times, so we need a function that asks how many times and then does it:
make_and_count_most<-function(how_many){
replicate(how_many,{
pack<-make_pack()
count_most(pack)
})
}
make_and_count_most(3)
## Flake Caramello Flake
## 4 2 4
And, finally, we take advantage of the power of modern computing by running this a whole heap of times. For curiosity – because the code was written to be clear, not to be fast – I’ll also see how long it takes on my three-year old laptop.
a_whole_heap <- 100000
system.time(results <- make_and_count_most(a_whole_heap))
## user system elapsed
## 13.281 0.041 13.322
table(results)
## results
## 2 3 4 5 6 7 8
## 16050 56165 22550 4626 565 42 2