1

I have a hard time figuring out how to write a program in R. I am suppose to bet 1$ on red, if I win I get 1$ and bet again, if I lose I double my bet. The program supposed to run until I win 10$ or bet becomes greater than 100. Here is my code:

    W=0
    B=1

    for(i=sample(0:1,1)){
      B<-1
      W<-0
      while(W<10 & B<=100){
        if(i=1){
          W<-W+B 
          B<-B
        }else{
          B<-2*B
        }
        print(B)
      }
    }

i determines if I lose or win. And I use print(B) to see the if program runs. At this point it doesn't, B just equals 1 no matter what.

AK9309
  • 761
  • 3
  • 13
  • 33

2 Answers2

5

To make the consequences of such gambling more obvious we can modify this program adding variables to store the total Win/Lose and the dynamics of this number.

W_dyn <- c()      # will store cumulative Win/Lose dynamics
W. <- 0           # total sum of Win/Lose        
step <- 0         # number of bet round - a cycle of bets till one of 
                  # conditions to stop happen:   W > 10 or B >= 100
while (abs(W.) < 1000)
{ B <- 1
  while (W < 10 & B <= 100)
  { i <- sample(0:1, 1)
    if (i == 1)
    { W <- W + B 
      B <- 1
    } else
    { W <- W - B
      B <- 2 * B
    } 
    print(B)
  }
  W. <- W. + W
  W <- 0
  step <- step + 1
  W_dyn[step] <- W.
  cat("we have", W., "after", step, "bet rounds\n")
}
# then we can visualize our way to wealth or poverty
plot(W_dyn, type = "l")

Bad Luck! :( It's My Day! :)

BTW, with condition of maximum possible B < Inf such gambling is always a waste of money in long run.

inscaven
  • 2,514
  • 19
  • 29
4

Your for loop doesn't make sense in this context. You should take another sample each time in the while loop.

  B = 1
  W = 0
  while(W<10 & B<=100){
    i=sample(0:1,1)
    if(i==1){
      W<-W+B 
      B<-B
    }else{
      B<-2*B
    }
    print(B)
  }

Also, in your original for loop you needed an extra right parentheses ) after the sample(0:1,1) before the loop started. Without it, the program doesn't run as expected.

Also, you should use == instead of = when describing logical equalities.

Max Candocia
  • 4,294
  • 35
  • 58
  • Thanks, edited the original post. For some reason when I run, the example you provided the sampling doesn't happen. `i` just stays equal to 1. Or if I actually write`if(i<-0)` etc. `i` stays equal to 0 – AK9309 May 06 '15 at 07:06
  • 1
    The `=` sign in `i=1` should be `==`, making `i==1`. – Max Candocia May 06 '15 at 07:21