Search code examples
matlabrandommontecarlo

How to add random values into an empty vector repeatedly without knowing when it would stop? How to count average number of steps?


Imagine the process of forming a vector v by starting with the empty vector and then repeatedly putting a randomly chosen number from 1 to 20 on the end of v. How could you use Matlab to investigate on average how many steps it takes before v contains all numbers from 1 to 20? You can define/use as many functions or scripts as you want in your answer.

v=[];
v=zeros(1,20);

for a = 1:length(v)
  v(a)=randi(20);
end

since v is now only a 1x20 vector, if there are two numbers equal, it definitely does not have all 20 numbers from 1 to 20

for i = 1:length(v)
  for j = i+1:length(v)
    if v(i)==v(j) 
      v=[v randi(20)];
      i=i+1;
      break;
    end
  end
end



for k = 1:length(v)
  for n = 1:20
    if v(k)==n
      v=v;
    elseif v(k)~=n
      a=randi(20);
      v=[v a];
    end
    if a~=n
      v=[v randi(20)];
      k=k+1;
      break;
    end
  end
end

disp('number of steps: ')
i*k

Solution

  • I'm not sure if I understand your question correctly, but maybe have a look at the unique() function.

    if

    length(unique(v)) == 20 
    

    then you have all values from 1:20 in your vector

    v = []
    counter = 0;
    while length(unique(v)) ~= 20
        a = randi(20);
        v=[v a];
        counter = counter +1
    end
    

    the value counter should give you the number of iterations needed until v contains all values.

    If you want to get the average amount of iterations by trial and error just make a look around this code and test it 10000 times and average the results form counter.