pr1g114413085
pr1g114413085

Reputation: 155

Practicing loops

I'm trying to improve my function writing skills and I'm a little confused on the proper structure of functions. I've searched a ton of examples, but none are that clear to me. My aim is to run the #RUN over and over section in a for loop and build a function which allows me to control the number of times I can loop it.

Currently, I've got to this point:

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),4)*100,"%"," of the time the Moose won")

Upvotes: 0

Views: 94

Answers (1)

Fnguyen
Fnguyen

Reputation: 1177

Besides my general problems with your question (please be more specific as to your actual problem) your for-loops have a wrong syntax. They should be like this:

for (val in sequence)
{
statement
}

So applied to your function they should look like this:

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

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

However the are not only syntactically wrong, also their content seems to be wrong.

E.g. in your second for-loop, the goose steps forward even though it should be the hunter. Also these are not two for-loops but should be an if-statement like this:

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

Finally the whole structure of your function seems strange (and has misleadingly named variables). Shouldn`t it be something like this:

dice_roll <- function(hunter,goose, 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)

Upvotes: 1

Related Questions