Created
October 22, 2019 12:49
-
-
Save DeeprajPandey/ea67fa18dee847d98be4521c959f6cb5 to your computer and use it in GitHub Desktop.
CS208 R Solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# q1 | |
pi_D <- function(n, P) { | |
if(length(P) != n) { | |
stop("Number of probablities should be same as n") | |
} | |
else { | |
# return an element from {1,2,3,...n} with probability P | |
elem = sample(1:n, 1, TRUE, P) | |
return(elem) | |
} | |
} | |
# print(pi_D(4, P)) | |
#q2 | |
pi_WS <- function(n, r) { | |
if (n%%1 != 0) { | |
stop("n has to be an integer") | |
} | |
if ((r < 1) || (r > n)) { | |
stop("Condition for r: 1 <= r <= n") | |
} | |
P = vector() | |
# initialise all probabilities to 1/n | |
for (p_i in c(1:n)) { | |
P = c(P, 1/n) | |
} | |
# maintain count | |
s = 0 | |
output = vector() | |
while(TRUE) { | |
# print(output) | |
if (length(output)) { | |
if (length(unique(output)) == r) | |
break; | |
} | |
x_i = pi_D(n, P) | |
output = c(output, x_i) | |
s = s+1 | |
} | |
return(s) | |
} | |
# print(pi_WS(5, 3)) | |
# q3 | |
pi_B <- function(n, p) { | |
return(rbinom(1, n, p)) | |
} | |
# n = 29 | |
# p = 1/5 | |
# print(pi_B(n,p)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment