R替换重复循环

时间:2017-05-03 16:07:46

标签: r performance loops vectorization repeat

我正在编写一个多次玩游戏的功能,并记录赢得游戏所需的中间步数,并在游戏大小列表中应用此功能。对于小尺寸(<100),它工作得相当好,但是对于较大的游戏来说需要不可行的长时间。我相当肯定这是因为玩游戏本身的代码是一个循环。

我对此很陌生,但我认为提高代码性能的方法是用某种矢量化函数替换重复循环。有没有人建议如何做到这一点?

plays <- function(c){
  outcomes <- replicate(10000,{
  # the list of results from 10,000 'plays' of the game size c
    bag <- c(1:c) 
    # an object containing the elements that are being played
    obj <- c(1:c)
    # an object with the indices of the elements of bag
    counter <- 0 
    # an object that counts the number of iterations 
    repeat{
      if(length(unique(bag))==1){
      # check to see if all objects in bag are identical
        break
        # then end the loop
      }
      # otherwise make one randomly selected object
      # in bag like another randomly selected object in bag
      k <- sample(obj,1,replace=F)
      l <- sample(obj[-k],1,replace=F)
      bag[l] <- bag[k]
      counter <- counter+1
      # and add 1 to the counter
    }
    counter 
    # output the number of steps to reach the end of the game 
  })
  median(outcomes)
  # output the median number of steps
}

0 个答案:

没有答案