返回平均转数超过1000次

时间:2018-11-12 19:35:45

标签: r for-loop simulation markov-chains

我对R还是比较陌生,因此我已经设置了一个模拟游戏的项目。我已经设计了游戏,并输入了代码,该代码将返回赢得游戏的转数,但是我仍然坚持如何模拟游戏1000次并返回平均值,尽管看起来很简单,但我就是无法解决。

返回赢取转数的代码:

    s=seq(1:25)
    current=vector()
    current[1]=1
    gameon=1
    turns=1
    while(gameon==1)
    {
      current[turns+1]=sample(s,1,replace=TRUE,prob=w[current[turns],])
      turns=turns+1
      if (current[turns]==25)
      {
       gameon=0
      }
    }

游戏代码和过渡矩阵:

w = matrix(0, nrow=25, ncol=25)
for (i in 1:25)                      #RED   - 1,2 down 2     3,4 back 3      5,6 
stay
{                                    #AMBER - 1,2 down 1   3,4 back 2      5,6 
forward 1
  if (i == 4)                        #GREEN - 1,2 stay     3,4 forward 1   5,6 
forward 2
  {
    w[i, i+2] = 1/3
    w[i,i+1] = 1/3           # effects on a state with a GREEN pub
    w[i,i] = 1/3
  }
  else if (i == 6)
  {
    w[i,i] = 1/3
    w[i,i+1] = 1/3
    w[i,i+2] = 1/3
  }
  else if (i == 7)
  {
    w[i,i-3] = 1/3
    w[i,i-2] = 1/3          # effects on a state with an AMBER pub
    w[i,i+1] = 1/3
  }
  else if (i == 12)
  {
    w[i,i] = 1/3
    w[i,i+1] = 1/3
    w[i,i+2] = 1/3
  }
  else if (i == 16)
  {
    w[i,i-3] = 1/3
    w[i,i-2] = 1/3         # effects on a state with a RED pub
    w[i,i+1] = 1/3
  }
  else if (i == 15)
  {
    w[i,i-10] = 1/3
    w[i,i-3] = 1/3         # effects on a state with a RED pub
    w[i,i] = 1/3
  }
  else if (i == 18)
  {
    w[i,i] = 1/3
    w[i,i+1] = 1/3         # effects on a state with a RED pub
    w[i,i+2] = 1/3
  }
  else if (i == 21)
  {
    w[i,i-10] = 1/3
    w[i,i-3] = 1/3
    w[i,i] = 1/3
  }
  else if (i == 24)
  {
    w[i,i-10] = 1/3
    w[i,i-3] = 1/3                  #horrible square to be stuck on, cant win from 
this square.
    w[i,i] = 1/3
  }
  else if (i <= 19)
  {
    w[i, seq(i+1,i+6)] = 1/6
  }
  else if (i==20)
  {
    w[i,seq(i+1,i+4)] = 1/6                
    w[i,i+5] = 2/6
  }
  else if (i==22)
  {
    w[i,seq(i+1,i+2)] = 1/6
    w[i,i+3] = 4/6
  }
  else if (i == 23)
  {
    w[i,i+1] = 1/6
    w[i,i+2] = 5/6
  }
  else if (i == 25)
  {
    w[i,i] = 1 #game finished
  }

}

我认为最好使用for循环,但我不知道如何设置它以返回平均匝数。

0 个答案:

没有答案