Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何从字符向量重复采样,直到出现特定序列?_R_Loops_Random - Fatal编程技术网

R 如何从字符向量重复采样,直到出现特定序列?

R 如何从字符向量重复采样,直到出现特定序列?,r,loops,random,R,Loops,Random,共有10张卡片写为“S”、“T”、“A”、“T”、“I”、“S”、“T”、“I”、“C”、“S”。 随机挑选一张卡片后,你将卡片放回原来的位置并混合。重复此操作,直到按顺序出现“S”、“A”、“T” x<-c("S","T","A","T","I","S","T","I","C","S") repeat{ print(sample(x,1,replace=TRUE))} x您可以使用: x<-c("S","T","A","T","I","S","T","I","C","S")

共有10张卡片写为“S”、“T”、“A”、“T”、“I”、“S”、“T”、“I”、“C”、“S”。 随机挑选一张卡片后,你将卡片放回原来的位置并混合。重复此操作,直到按顺序出现
“S”、“A”、“T”

x<-c("S","T","A","T","I","S","T","I","C","S")
repeat{
  print(sample(x,1,replace=TRUE))}
x您可以使用:

x<-c("S","T","A","T","I","S","T","I","C","S")

pre_last <- NULL
last <- NULL
curr <- NULL

repeat{
  curr <- sample(x,1,replace=TRUE)
  if(curr == "T")
    if(last == "A" && pre_last == "S")
        break
  pre_last <- last
  last <- curr
}

# Result
pre_last
last
curr
x这里有一种方法

tmp <- c(NA, sample(x, 2, replace = TRUE))
k <- 0
while (!identical(tmp, c("S", "A", "T"))) {
  tmp <- c(tmp[-1], sample(x, 1))
  k <- k + 1
  }
tmp另一种解决方案:

s = sapply(1:3,function(i) {sample(x,1,replace=TRUE)})
print(s)
repeat{
  if(s[1]=="S" & s[2]=="A" & s[3]=="T")
    break
  else { 
    s=s[-1]
    s=c(s,(sample(x,1,replace=TRUE)))
    print(s)
  }
}
您可以这样做:

set.seed(1)
i <- 1
wanted <- c("S","A","T")
res <- c()
while(TRUE){
    r <- sample(x,1,replace = TRUE)
    res <- c(res, r)
    if(r==wanted[i])
        i <- i+1
    else i <- 1

    if(i==(length(wanted)+1)) break
}

> res
 [1] "A" "T" "S" "S" "A" "C" "S" "T" "T" "S" "A" "T"
set.seed(1)
我