Probability of at least 1 even number using while loop

3 views (last 30 days)
Find the probability of rolling at least 1 even number using 3 dice. You cannot use any vectors or matrices, or any vectorized operations. Instead, do it using loops. Notice that in each trail, to see if there is at least one even number, there is no need to always inspect the value of each of the dice. No need to inspect the remaining dice as soon as an even number is encountered. Thus a while-loop should be used to handle that part of the problem
I have no idea how to use the while loop in this problem
clear;clc;
nDice = 3; % Number of dice
nTrials = 1e6; % Number of trials
for i = 1:nTrials
end
  5 Comments
A. Sawas
A. Sawas on 8 Apr 2019
Guillaume and John D'Errico, you guys are awesome in finding short optimum solutions !
but I am not sure why you focused on finding the answer to the problem than the purpose of solving it using within the prescribed constraints. (using while loop, simulating trials, having there dices, not using vectors, etc.)
I think regardless whatever this problem and contraints seemed to be unlogical, one would learn something solving it.
Guillaume
Guillaume on 8 Apr 2019
I think regardless whatever this problem and contraints seemed to be unlogical, one would learn something solving it.
Yes, you learn the wrong way of using matlab. It teaches you to use loops where they're inefficient. It teaches you to think about this sort of problems in a way that is inefficient. Unfortunately, we can see the result in this forum, where we spend a lot of effort unteaching that mindset. People come here with code that have multiple loops saying that it is too slow.
This problem is better though of as:
  • generate all possible dice rolls (there's only 216). That can be done efficiently in one line with ndgrid or dec2base. You could indeed use one (or three) loops to generate all these rolls. That'd be slower and more lines of code.
  • find which of these dice rolls have even numbers. Again, the efficient way is a mod test on the whole lot. Here you're asked to use a while loop on a single roll. This in my opinion is completely absurd.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 8 Apr 2019
For each trial Initialize dice remaining to 3. While number of dice remaining is positive Decrement dice remaining. roll a die. If it was even add 6 to power of remaining dice to statistics and set dice remaining 0.
After all trials divide statistics by 216 times number of trials.

Torsten
Torsten on 8 Apr 2019
Maybe of interest for checking the result of the Monte Carlo simulation:
P(rolling at least one even number with 3 dice) =
1- P(rolling only odd numbers with three dice) =
1 - 3^3 / 6^3

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!