我尝试自己写一个这样的函数。这是尝试:
RL_seq <- function(n_L = 10, n_R = 10, max_consec = 2, initial_seq = NULL) {
while(n_L > 0 | n_R > 0){
side <- sample(c("R", "L"), 1)
if (side == "R" & n_R > 0 & length(grep("R", tail(initial_seq, max_consec))) != max_consec) {
initial_seq <- append(initial_seq, side)
n_R <- n_R - 1
} else if (side == "L" & n_L > 0 & length(grep("L", tail(initial_seq, max_consec))) != max_consec) {
initial_seq <- append(initial_seq, side)
n_L <- n_L - 1
}
}
print(initial_seq)
}
# The function does not stop with the following seed
set.seed(1)
RL_seq()
但是,代码是否卡住取决于机会。我还希望可以更改序列的规则(例如,允许 3 个连续的 R),但如果我触及参数,代码往往会中断。此时,如果我可以使用默认参数运行它并且不会卡住,我会很高兴。我四处寻找但找不到答案。任何帮助表示赞赏。另外,我对编程比较陌生,而且是自学的,以前从未在堆栈溢出上发布过任何内容,所以我提前道歉。
RL_seq <- function(n_L = 10, n_R = 10, max_consec = 2) {
seq = c(rep("L", n_L), rep("R", n_R))
consec = max(rle(seq)[1]$lengths)
while(consec > max_consec) {
seq = sample(seq, length(seq), replace = FALSE)
consec = max(rle(seq)[1]$lengths)
}
seq
}
RL_seq()