Get startedGet started for free

Can this loop run in parallel (1)?

The following piece of code implements a simple dice game. The game is as follows:

  • Initialize: total <- 0.
  • Roll a single die and add it to total.
  • If total is even, reset total to zero.
  • If total is greater than 10, the game finishes.

This is straightforward to code in R

total <- no_of_rolls <- 0 # Initialize
while(total < 10) {
  total <- total + sample(1:6, 1)

  if(total %% 2 == 0) total <- 0  # If even. Reset to 0

  no_of_rolls <- no_of_rolls + 1
}
no_of_rolls

Do you think this algorithm can be (easily) run in parallel?

This exercise is part of the course

Writing Efficient R Code

View Course

Hands-on interactive exercise

Turn theory into action with one of our interactive exercises

Start Exercise