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
Aucun commentaire:
Enregistrer un commentaire