A random sequence from a fixed ensemble containing at least one of the characters

I am trying to create a random sequence of a fixed number of characters that contains at least one of each character.

For example, having an ensemble

m = letters[1:3]

I would like to create a sequence of N = 10 elements that contain at least one of each character m , for example

 a a a a b c c c c a 

I tried with sample(n,N,replace=T) , but in this case also a sequence like

 a a a a a c c c c a 

can be generated that does not contain b .

+5
source share
2 answers
 f <- function(x, n){ sample(c(x, sample(m, n-length(x), replace=TRUE))) } f(letters[1:3], 5) # [1] "a" "c" "a" "b" "a" f(letters[1:3], 5) # [1] "a" "a" "b" "b" "c" f(letters[1:3], 5) # [1] "a" "a" "b" "c" "a" f(letters[1:3], 5) # [1] "b" "c" "b" "c" "a" 
+8
source

Josh O'Briens answer is a good way to do this, but doesn't provide much input validation. As I already wrote, he could also provide my answer. It's almost the same thing, but will take care of checking things as soon as you look at unique items and making sure there are enough unique items to ensure that you get at least one of them.

 at_least_one_samp <- function(n, input){ # Only consider unique items. items <- unique(input) unique_items_count <- length(items) if(unique_items_count > n){ stop("Not enough unique items in input to give at least one of each") } # Get values for vector - force each item in at least once # then randomly select values to get the remaining. vals <- c(items, sample(items, n - unique_items_count, replace = TRUE)) # Now shuffle them sample(vals) } m <- c("a", "b", "c") at_least_one_samp(10, m) 
+5
source

Source: https://habr.com/ru/post/1204602/


All Articles