set.seed(19104)
#Create a coin that comes up heads 67% of the time.
coin <- c(rep(1,67), rep(0,33))
#Repeatedly sample seeing how often we get 0 heads:
no.heads <- rep(NA, 100000)
for(i in 1:length(no.heads)){
  flip <- sample(coin, 3)
  no.heads[i] <- sum(flip)==0
}
mean(no.heads)


set.seed(19104)
coin <- c(rep(1,67), rep(0,33))

two.heads <- rep(NA, 100000)

for(i in 1:length(two.heads)){
  flip <- sample(coin, 3, replace = T)
  two.heads[i] <- sum(flip)==2
}

mean(two.heads)


set.seed(19104)
coin <- c(rep(1,67), rep(0,33))

two.heads <- rep(NA, 100000)

for(i in 1:length(two.heads)){
  #Change 3 to 10 in the below:
  flip <- sample(coin, 10, replace = T)
  two.heads[i] <- sum(flip)==2
}

mean(two.heads)


#Creating a binomial function:
prob.k <- function(n,k,p){
  choose(n,k)*p^(k) * (1-p)^(n-k)
}
#Test function
prob.k(3,2,.67)

probs <- prob.k(35,0:35,.67)

#Graphing
plot(0:35, probs, xlab="Number of Completed Passes", ylab="Probability")

#Via Simulation

#Generate a vector to sample from the comes up 1 67% of the time and 0 33% of the time:
mahomes <- c(rep(1,67), rep(0,33))
result <- NA

for(i in 1:10000){
  result[i] <- sum(sample(mahomes, 35, replace=T))
}

hist(result, xlim=c(0,35), ylim=c(0,0.15),freq=F )
points(0:35, probs, style="b", col="darkblue", pch=16)



#Bernoulli RV PMF

plot(c(0,1), c(.5,.5), pch=16, xlim=c(-1,2))
segments(0,0,0,.5)
segments(1,0,1,.5)


#Drawing a Bernoulli RV CDF

plot(c(0,1), c(0,.5), ylim=c(0,1), xlim=c(-1,2))
points(c(0,1), c(.5,1), pch=16)
segments(-5,0,0,0)
segments(0,.5,1,.5)
segments(1,1,5,1)

dbinom(x=0:10, size=10, prob=.3)

probs <- dbinom(x=0:10, size=10, prob=.3)
plot(0:10, probs, xlab="Number of Successes", ylab="P(X=x)", pch=16,
     main="PMF for n=10 p=.3")

pbinom(0:10, 10, .3)

probs <- pbinom(0:10, 10, .3)
plot(0:10, probs, xlab="Number of Successes", 
     ylab="P(X <= x)", main="CDF for n=10 p=.3", pch=16)

dbinom(0.5, 10, .3)

pbinom(24, 35, .665)

probs <- dbinom(0:35, 35, .67)
plot(0:35, probs, xlab="Number of Heads in 35 Flips", ylab="P(X=x)", pch=16)

set.seed(19104)
thirty.draws <- rbinom(30, 35, .67)
thirty.draws

selection <- sort(unique(thirty.draws))
probs.selection <- prop.table(table(thirty.draws))
plot(0:35, probs, pch=16, xlab="Number of Heads", ylab="Probability", ylim=c(0,.2))
points(selection, probs.selection, pch=16, col="firebrick")

pi <- seq(0,1,.001)
plot(pi, pi*(1-pi), type="l", xlab="pi", ylab="Variance",
     main="Variance of Bernoulli RV")
