固定集合中的随机序列,每个序列至少包含一个字符 [英] Random sequence from fixed ensemble that contains at least one of each character

查看:139
本文介绍了固定集合中的随机序列,每个序列至少包含一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从固定数量的字符中生成随机序列,其中每个字符至少包含一个.

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

例如拥有合奏

m = letters[1:3]

我想创建一个由N = 10个元素组成的序列,每个元素至少包含一个m个字符,例如

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

a
a
a
a
b
c
c
c
c
a

我尝试了sample(n,N,replace=T),但是这种方式也像

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

a
a
a
a
a
c
c
c
c
a

可以生成不包含b

.

can be generated that does not contain b.

推荐答案

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"

这篇关于固定集合中的随机序列,每个序列至少包含一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆