Problem 1

# probability of both balls being of the same color

m = 100000
agree = logical(m)
urn1 = c("B","G")
urn2 = c("W","G")
for(i in 1:m){
  draw1 = sample(urn1, 1)
  draw2 = sample(urn2, 1)
  agree[i] = (draw1 == draw2)
}
SameColor <- mean(agree)
SameColor
## [1] 0.24875
# probability of getting exactly one gold ball

m = 100000
agree = logical(m)
urn1 = c("B","G")
urn2 = c("W","G")
for(i in 1:m){
  draw1 = sample(urn1, 1)
  draw2 = sample(urn2, 1)
  agree[i] = (draw1 == "G" & draw2 != "G") | (draw1 != "G" & draw2 == "G")
}
Exactly1Gold <- mean(agree)
Exactly1Gold
## [1] 0.50166
# probability of getting no gold balls

m = 100000
agree = logical(m)
urn1 = c("B","G")
urn2 = c("W","G")
for(i in 1:m){
  draw1 = sample(urn1, 1)
  draw2 = sample(urn2, 1)
  agree[i] = (draw1 != "G" & draw2 != "G")
}
NoGold <- mean(agree)
NoGold
## [1] 0.25237
Prob <- cbind(SameColor, Exactly1Gold, NoGold)
Prob
##      SameColor Exactly1Gold  NoGold
## [1,]   0.24875      0.50166 0.25237
barplot(Prob, ylim = c(0, 0.5), ylab = "Probability", col = "Blue")

Problem 2

FlipCoin <- function(n){sample(0:1, n, rep = TRUE)} # define the coin toss function where there 
                                                    # are two possible outcomes 0 ("Tails") and
                                                    # 1 ("Heads") and n is the number of iterations

x = NULL
iterations = NULL
RelFreq = NULL
Prob = NULL

for (i in 1:100) {
  x = FlipCoin(i)   # x gives the total number of heads in i number of tosses
  RelFreq = sum(x)/i 
  
  Prob <- c(Prob, RelFreq)  # d gives the probability of heads in i number of tosses
  iterations <- c(iterations,i)        
}
plot(iterations, Prob, type ="l", ylim = c(0,1))  # line plot shows that as the number of iterations

                                                  # increase from 0 to 100, the probability of heads
                                                  # gets closer to 0.5