Search code examples
rsampledice

Changing values of a dice roll


So let's say I roll 5 dice.

The code to simulate the rolls would be

Rolls<-sample(1:6, 5, replace=TRUE)

and that's if I want to store my rolls under the object Rolls.

Now let's say for some reason I don't want there to be more than 2 sixes. That means if I roll, for example, 6 3 5 6 6 1 would I be able to re-roll one of the 6 values into a new value so that there are only 2 values of 6 and 4 values that are not 6?

Any support would be appreciated.

Thanks in advance


Solution

  • A solution without loops could be:

    condition = which(Rolls==6)
    if(length(condition)>=3){
      Rolls[condition[3:length(condition)]] = sample(1:5, length(condition)-2, replace=TRUE)
    }
    

    condition states the places in Rolls with 6's, if there's more than 2, you select the third one onward Rolls[condition[3:length(condition)]] and re-sample them.

    And the second question could be something like:

    remove = 3
    Rolls = Rolls[-which(Rolls==remove)[1]]
    

    You can easily put those into functions if you like

    Edit 1

    To make the second answer a bit more interactive, you can build a function for it:

    remove.roll = function(remove, rolls){
       rolls = rolls[-which(rolls==remove)[1]]}
    

    And then the user can call the function with whatever remove he likes. You can also make a program that takes information from the prompt:

    remove = readline(prompt="Enter number to remove: ")
    print(Rolls = Rolls[-which(Rolls==remove)[1]])