user2800103
user2800103

Reputation: 3

Generate a random number until it matches a user's input

Say, a user has to enter a number in between a specified range, and that you want MatLab to track the number of times it took to generate a number greater than the user's selected number.

How would you put conditions on the randi function, and how would you track the number of tries?

I was thinking of setting the user's input to variable a, then stating a 'while' condition holding that the input value "a" has to be in between a range I specify, and if true, start the randi function with its conditions; if value entered isn't within specified range, display an error message.

Upvotes: 0

Views: 507

Answers (1)

Buck Thorn
Buck Thorn

Reputation: 5073

Here's a simple implementation which uses rand (pick a number between 0 and 1) rather than randi:

buff=1000; % number of random numbers to test with each iteration... 
yn=1;
while yn
    num=input('Enter a number between 0 and 1 >> ');
    nn = -buff;
    found=[];
    while isempty(found)
       nn= nn+buff;
       found=find(rand(buff,1)>num,1,'first');
    end
    nn=nn+found;
    disp(nn)
    yn=input('Would you like to try again? (0=no,1=yes) >> ');
end

Variable nn contains the number of trials prior to the first success.

A test run looks like this:

Enter a number between 0 and 1 >> 0.999
        1325
Would you like to try again? (0=no,1=yes) >> 0

Modification to use randi should be straightforward.

Upvotes: 1

Related Questions