0

I am creating a code to simulate a simple slot machine. In my function 'slot_machine', I keep getting an issue with my 2nd else if statement

else if (drum1==2|3|4|5 & drum2==2|3|4|5 & drum3==2|3|4|5){    
payout <- 114}

Even when the conditions are not met, it keeps making the payout value $114. I'm relativity new to coding so this might be a stupid mistake. If you have any suggestions or ideas, I would greatly appreciate them.

Thank you.

cat("\014")
# d)
slot_machine <- function(payout){
  drum1 <- 1
  drum2 <- 1
  drum3 <- 7
  if (drum1==drum2 & drum2==drum3){
    if (drum1==1){
      payout <- 3000
    }
    else if (drum1==2|3|4|5){
      payout <- 114
    }
    else{
      payout <- 0
    }
  }

  else if (drum1==2|3|4|5 & drum2==2|3|4|5 & drum3==2|3|4|5){
    payout <- 114
  }

  else{
    payout <- 0
  }
}

number_of_plays <- 5
total_gain = number_of_plays*2
array = rep(NA,number_of_plays)
total_loss <- 0
for (i in 1:number_of_plays){
  array[i] <- slot_machine(payout)
  total_loss <- total_loss + array[i]
}
profit = total_gain - total_loss
Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
Rotoson
  • 9
  • 2
  • 3
    Instead of using for example `drum1==2|3|4|5`, you should use `drum1 %in% c(2,3,4,5)` or `drum1 %in% 2:5` – Jaap Jan 28 '16 at 20:15
  • Do you intend to test whether `drum1` is one of `2|3|4|5`? In that case, try using `drum1 %in% c(2, 3, 4, 5)`. – Gopala Jan 28 '16 at 20:16

1 Answers1

2

In addition to the comments made above, there are other improvements that can be made to your simulation:

slot_machine <- function() {
        #only one 'drums' variable with 3 values from 1 to 5
        drums <- sample(1:5,3, replace=T)
        #use length of unique drums. It will be equal to 1 when drums are the same
        if(length(unique(drums)) == 1) {
                #'1' is the biggest payoff '3000' for wins, '114' for other matches
                #We use 'return()' bc it terminates the function.
                if(drums[1] == 1) return(3000) else return(114)
        } else {
                #for losses
                return(0)
        }    
}

#simulate a game of slots. User chooses how many times to play
#and the cost per play
play_slots <- function(plays, cost_per_play) {

        #gain starts at zero
        total_gain <- 0

        #simulate games
        for(i in 1:plays) {
             total_gain <- total_gain + slot_machine()   
        }

        #calculate profits
        profit <- total_gain - cost_per_play*plays
        return(profit)
}

#A game example. 100 plays, 1 unit of cost per play
set.seed(128)
play_slots(100, 1)
[1] 356
Pierre L
  • 28,203
  • 6
  • 47
  • 69