wjddmsdl
wjddmsdl

Reputation: 31

Matlab roll one dice game by using python and for sentence to add number

enter image description here

The question is this. As a result of consideration, I think if this condition is satisfied the code will be success.

Set n = 0, generate one of the integers 1~6 uniformly, Add a win if 1 was generated and add a lose otherwise, n++, 4. go back to 1 if n

but I don't know how to make it.can you please help me

N=100;
win=0;
lose=0;
a=randi([1 6],1,1);    
n=0;
p=0;
while n<N
  if a==1
    win=win+1;
    else
      lose=lose+1;
      n++
  endif
endwhile

Upvotes: 0

Views: 103

Answers (1)

il_raffa
il_raffa

Reputation: 5190

There are a couple of errors in your code:

  • you are generating only one random number, since the call to randi is outside of the while loop. So you are testing a==1 N times with a having always the same value
  • a part from the previous error, you are incrementing the counter n only in the else condition

A possible implementation could be the following in which you can incluide the code in a for loop to check the percentage of win wrt the number of attempts; you can also add the reference value of 1/6 %.

% Define the winning number
win_value=1
for N=1:1000
   % Generate N random values
   result=accumarray(randi([1 6],N,1),1);
   % Count the wins 
   win(N)=result(win_value);
   Pct_win(N)=win(N)/N*100;
end
plot(Pct_win)
hold on
plot([1 N],[1/6 1/6]*100,'r','linewidth',2)
xlabel('Attempts')
ylabel('Win %')
legend('Wins','Ref')

enter image description here

Upvotes: 1

Related Questions