lundi 16 juillet 2018

Repeat a function until conditions are met in r using a while loop

This may not be the most efficient way for doing this, but I've created a code for a fruit machine (that works), from the help of a book (not sure if I can share the title, but it is very good for noobs). However this code is very simple, it runs a function that calls two other functions, in order:

  1. pull() simulates the wheel mechanism by randomly selecting characters from a pre-determined vector.
  2. prize() analyses pull() to add a value to the symbols by using a lookup table.

The code works, but I wanted to modify it so that the code runs until it reaches the jackpot which is three diamonds; "DD". I also wanted it to quantify all other responses until it reaches this target, so I tried a while loop, which does not seem to produce anything:

 play2 <- function(){
  response <- pull()

  # I put the while loop straight after calling the first function.

  while (sum(response == "DD") != 3) {

  # I set the condition so that if the jackpot is not achieved, the 
  # while loop causes the other responses to be investigated. It 
  # it determines this by counting booleans. 

    # The following assignments are designed to begin the count for how
    # many responses that are considered prizes occur, and how often no
    # prize occurs.

    cherry_prize <- 0
    B_prize <- 0
    BB_prize <- 0
    BBB_prize <- 0
    seven_prize <- 0
    no_prize <- 0

    if ("C" %in% response){
      cherry_prize <- cherry_prize + 1



      # A cherry prize occurs if any "C" is returned. The following
      # statements will asses the other non-jackpot three of a kinds.

    }
    else if (sum(response == "B") != 3) {
      B_prize <- B_prize + 1
    }
    else if (sum(response == "BB") != 3) {
      BB_prize <- BB_prize + 1
    }
    else if (sum(response == "BBB") != 3) {
      BBB_prize <- BBB_prize + 1
    }
    else if (sum(response == "7") != 3) {
      seven_prize <- seven_prize + 1
    }
    else {
      no_prize <- no_prize + 1
    }
  }

  # After the jackpot is achieved, the number of other prizes (or lack
  # thereof) that were returned are quantified, prior to the jackpot 
  # were won. The jackpot triplicate would then also be returned and
  # quantified.

  print(cherry_prize)
  print(B_prize)
  print(BB_prize)
  print(BBB_prize)
  print(seven_prize)
  print(no_prize)
  print(response)
  score(response)
}

Hope I have provided enough information. All help received very gratefully, and hope it can help others.

Aucun commentaire:

Enregistrer un commentaire