Chapter 1.1.3 Exercises
In [13]:
# The Birthday Problem
sample(x = 1:365, size = 25, replace = TRUE)
anyDuplicated(sample(x = 1:365, size = 25, replace = T))
trials <- replicate(n = 10000,expr = anyDuplicated(sample(x = 1:365, size = 25, replace = T)))
head(trials)
mean(trials == 0)
In [14]:
# with leap years.
sample(x = 1:366, size = 25, replace = TRUE)
anyDuplicated(sample(x = 1:366, size = 25, replace = T))
trials <- replicate(n = 10000,expr = anyDuplicated(sample(x = 1:366, size = 25, replace = T)))
head(trials)
mean(trials == 0)
In [15]:
# Three numbers are picked uniformly at random from the interval (0,1). What is the probability that a triangle can formed whose side-lengths are the three numbers that you chose?
# We need to check whether the sum of the two smaller numbers is larger than the largest number. We use the sort command to sort the three numbers into increasing order, as follows:
mean(replicate(10000, {x = sort(runif(3,0,1)); sum(x[1:2]) > x[3];}))
In [21]:
# Suppose that you have 10 boxes, numbered 0-9. Box i contains i red marbles and 9−i blue marbles. You perform the following experiment. You pick a box at random, draw a marble and record its color. You then replace the marble back in the box, and draw another marble from the same box and record its color. You replace the marble back in the box, and draw another marble from the same box and record its color. So, all three marbles are drawn from the same box.
# If you draw three consecutive red marbles, what is the probability that the 4th marble will also be red?
library(dplyr)
#box <- sample(c(0:9), 1, replace = TRUE) ; box
#r = rep("R", box) ; r
#b = rep("B", 9-box); b
#mbox <- union_all(r, b) ; mbox
#draw <- sample(mbox, 4, replace = TRUE) ; draw
mean(replicate(1000000, {box <- sample(c(0:9), 1, replace = TRUE) ;r = rep("R", box) ; b = rep("B", 9-box); mbox <- union_all(r, b) ; draw <- sample(mbox, 4, replace = TRUE); sum(draw == "R") == 4}))
box; mbox; draw
In [ ]:
library(dplyr)
box <- sample(c(0:9), 1, replace = TRUE) #selecting a box out of 10 boxes.
r = rep("R", box) # the red marbles in the selected box.
b = rep("B", 9-box) # the blue marbles in the selected box.
mbox <- union_all(r, b) # total marbles in the selected box.
draw <- sample(mbox, 4, replace = TRUE) # the marbles drawn in 4 draws.
# added sum command to ensure that the first three outcomes are red and the fourth, too.
mean(replicate(10000, {box <- sample(c(0:9), 1, replace = TRUE) ; draw <- sample(mbox, 4, replace = TRUE);
(sum(draw[1:3] == "R") == 3 && draw[4] == "R")}))