Skip to content

Instantly share code, notes, and snippets.

@jedifran
Created December 13, 2011 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jedifran/1470102 to your computer and use it in GitHub Desktop.
Save jedifran/1470102 to your computer and use it in GitHub Desktop.
upstream challenge
#Challenge:
#Given the following set of numbers {49,8,48,15,47,4,16,23,43,44,42,45,46}. A function picks a random subset of size 6, and takes the minimum, what is the expected value of this function.
#put set of numbers into a container
test.set <- c(49,8,48,15,47,4,16,23,43,44,42,45,46)
#This function picks a random subset of size 6 and takes the minimum
upstream.fxn <- function(test.set) {min(sample(test.set,6));}
#to find the expectation of this function (by simulation) we resample a large number of times:
expectation <- mean(unlist(lapply(1:2000000, function(x) upstream.fxn(test.set))))
> system.time(expectation <- mean(unlist(lapply(1:20000000, function(x) upstream.fxn(test.set)))))
user system elapsed
721.370 11.186 846.715
> expectation
[1] 8.818875
# the required function will tend towards 8.82 in the long run.
#i.e the expectation of min(sample(test.set,6)) is approximately 8.82
#alternative method using a loop - which takes considerably longer to run!
aa <- 0
for(it in 1:20000){
aa[it] <- mean(unlist(lapply(1:it, function(x) upstream.fxn(test.set))))
}
mean(aa)
> mean(aa)
[1] 8.818985
summary(aa)
> summary(aa)
Min. 1st Qu. Median Mean 3rd Qu. Max.
4.000 8.768 8.817 8.819 8.867 23.000
plot(c(1:20000),aa, type="l")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment