Skip to content

Instantly share code, notes, and snippets.

@jedifran
Created December 13, 2011 02:04
Show Gist options
  • Select an option

  • Save jedifran/1470102 to your computer and use it in GitHub Desktop.

Select an option

Save jedifran/1470102 to your computer and use it in GitHub Desktop.

Revisions

  1. jedifran revised this gist Dec 13, 2011. 1 changed file with 21 additions and 0 deletions.
    21 changes: 21 additions & 0 deletions upstream_challenge.R
    Original file line number Diff line number Diff line change
    @@ -22,3 +22,24 @@ expectation <- mean(unlist(lapply(1:2000000, function(x) upstream.fxn(test.set))

    # 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")
  2. jedifran created this gist Dec 13, 2011.
    24 changes: 24 additions & 0 deletions upstream_challenge.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@


    #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