练习建筑功能R(猎人之谜)

我正在尝试提高我的函数编写技能,并对函数的正确结构有些困惑。我搜索了很多示例,但是我都不清楚。我的目标是在#RUN over and over循环中运行for部分,并构建一个函数,该函数使我可以控制循环的次数。

目前,我已经明白了这一点:

set.seed(123)
#Start but setting the conditions and being the Win Lose counters 
Count_Win_Hunt=0 
Count_Win_Moose=0 

#RUN over and over
Hunter=1
Moose=7
win=0

while(win != 1){ a = sample(1:6,1) # dice roll 
if( a<= 4) {Moose = Moose+a} else{Hunter = Hunter+a}
if( Hunter >= Moose  ) { Count_Win_Hunt = Count_Win_Hunt +1 } else if( Moose >= 12) {Count_Win_Moose = Count_Win_Moose + 1}

if( Hunter >= Moose || Moose >= 12 ) {win = win+1} else {
  #if not condition not meet roll again
  a = sample(1:6,1) # dice roll
  if( a<= 4) {Moose = Moose+a} else{ Hunter = Hunter+a}}}


# calculated the average win rates 
paste0( round(Count_Win_Hunt/(Count_Win_Hunt+Count_Win_Moose),4)*100,"%"," of the time the Hunter won")
paste0( round(Count_Win_Moose/(Count_Win_Hunt+Count_Win_Moose)," of the time the Moose won")
mz1bw6l16 回答:练习建筑功能R(猎人之谜)

除了我的一般问题(请更具体地说明您的实际问题)之外,您的for循环语法错误。他们应该是这样的:

for (val in sequence)
{
statement
}

因此应用于您的函数时,它们应如下所示:

for (val in c(1:4))
{
probability + (hunter,goose+val,num+1)
}

for (val in c(5:6))
{
probability + (hunter,num+1)
print probability
}

但是,不仅在语法上是错误的,而且它们的内容似乎也是错误的。

例如在第二个for循环中,鹅向前走,即使它应该是猎人。同样,这些不是两个for循环,而应该是这样的if语句:

if (val <= 4) {
probability + (hunter,num+1)
}
else {
probability + (hunter+val,goose,num+1)
}

最后,您的函数的整个结构似乎很奇怪(并且具有误导性的变量名称)。不应该是这样的:

dice_roll <- function(hunter,win){
# While to check for winning condition
while(win != 1){
 dice_roll = sample(1:6,1) # simulate dice roll

 # If statement depending on dice roll,increasing value of hunter or goose by dice roll

 # Change win condition
 If(hunter >= goose){
  win <- 1
 }
}

dice_roll(1,7,0)
本文链接:https://www.f2er.com/3144831.html

大家都在问