Skip to content

Instantly share code, notes, and snippets.

@andrie
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrie/340ddb6d9839783d20af to your computer and use it in GitHub Desktop.
Save andrie/340ddb6d9839783d20af to your computer and use it in GitHub Desktop.
Computing the probability of drawing two identical numbers out of a hat
# Computing the probability of drawing two identical
# numbers out of a hat
# Incorrect - binomial distribution ---------------------------------------
# Use pbinom() to compute a probability curve for binomial
# distribution
x <- pbinom(q = 0:10, size = 10, prob = 0.1)
plot(0:10, 1-x, type="b", lwd=2,
main="Incorrect analysis - binomial distribution",
xlab=NA,
ylab="Probability")
# Computing all permutations ----------------------------------------------
# Use a function inside permn() to reduce memory consumption. Rather
# than returning the entire permutation in each step, return the
# count of positional matches
library(combinat)
y <- permn(1:10, function(x)sum(x == 1:10))
z <- table(unlist(y))
plot(z/sum(z), type="b",
main="Permutation analysis",
xlab=NA,
ylab="Probability")
# Simulating the draws ----------------------------------------------------
n <- 1e6
z <- replicate(n, sum(sample.int(10) == 1:10))
plot(table(z)/n, type="b",
main="Using simulation rather than permutation",
xlab=NA,
ylab="Probability")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment