### Problem 6.8

rX <- function(n, p, v)
{
  U <- runif(n)
  X <- rep(0,n)
   w1 <- which(U <= p[1])
  X[w1] <- v[1]
    w2 <- which( (U > p[1]) & (U <= sum(p[1:2])) )
  X[w2] <- v[2]
   w3 <- which( (U > sum(p[1:2])) & (U <= sum(p[1:3])) )
  X[w3] <- v[3]
    w4 <- which( ((U > sum(p[1:3]))) & (U <= sum(p[1:4])) )
  X[w4] <- v[4]
   w5 <- which( ((U > sum(p[1:4]))) & (U <= sum(p[1:5])) )
  X[w5] <- v[5]
    w6 <- which( ((U > sum(p[1:5]))) & (U <= sum(p[1:6])) )
  X[w6] <- v[6]
   w7 <- which( ((U > sum(p[1:6]))) & (U <= sum(p[1:7])) )
  X[w7] <- v[7]
   w8 <- which( ((U > sum(p[1:7]))) & (U <= sum(p[1:8])) )
  X[w8] <- v[8]
  w9 <- which( ((U > sum(p[1:8]))) & (U <= sum(p[1:9])) )
  X[w9] <- v[9]
  w10 <- which(  (U > sum(p[1:9])) )
  X[w10] <- v[10]
    return(X)
  }
##Build distributions to sample from.

oatsp<-c(.05,.07,.09,.11,.15,.25,.1,.09,.06,.03)
oatsr<-c(0,.5,1,1.5,2,3,4,5,7.5,10)
oatsdist<-rX(10000,p=oatsp,v=oatsr)
hist(oatsdist)

peasp<-c(.1,.2,.2,.3,.1,.1)
peasr<-c(0,.5,1,1.5,2,3)
peasdist<-(rX(10000,peasp,peasr))
hist(peasdist)

beansr<-c(0,1,3,4.5)
beansp<-c(.2,.4,.3,.1)
beansdist<-rX(10000,p=beansp,v=beansr)
hist(beansdist)

barr<-c(0,.5,1,3.5)
barp<-c(.2,.4,.3,.1)
bardist<-rX(10000,p=barp,v=barr)
hist(bardist)

Item<-c("Oats","Peas","Beans","Barley")
cost<-c(1.05,3.17,1.99,.95)
sell<-c(1.29,3.76,2.23,1.65)
maxD<-c(10,8,14,11)
data<-data.frame(Item,cost,sell,maxD)

trueD_90<-c()
TotalC<-c()
TotalP<-c()
TotalR<-c()

for(i in 1:10000) {
  
  trueD_90<-c(sum(sample(oatsdist,90)),sum(sample(peasdist,90)),sum(sample(beansdist,90)),sum(sample(bardist,90)))
  
  TotalC[i]<-sum(data$cost*trueD_90)
  TotalR[i]<-sum(data$sell*trueD_90)
  TotalP[i]<-TotalR[i]-TotalC[i]
  
}

##Histogram of Costs
summary(TotalC)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   851.1   984.9  1013.0  1013.0  1041.0  1195.0
hist(TotalC)

#Normal

## Revenue
summary(TotalR)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    1047    1199    1233    1233    1266    1444
hist(TotalR)

## Profit

summary(TotalP)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   181.0   213.0   219.5   219.7   226.2   259.1
hist(TotalP)

###10,000 Replications of random simulations with the given distributions yields a mean Profit of 221.