How to avoid duplication of random numbers?
조회 수: 2 (최근 30일)
이전 댓글 표시
clc;
clear all;
n=10;
rng(1);
reply_timer=randi(10);
fprintf('The reply_timer is %i\n',reply_timer);
i=1;
t=15;
while(1)
if(reply_timer<t)
rng 'shuffle'
node=randi(n);
fprintf('The node %d is selected for simulation\n',node);
reply_timer=reply_timer+1;
else
break;
end
end
Output:
The reply_timer is 5
The node 8 is selected for simulation
The node 1 is selected for simulation
The node 3 is selected for simulation
The node 1 is selected for simulation
The node 5 is selected for simulation
The node 7 is selected for simulation
The node 7 is selected for simulation
The node 7 is selected for simulation
The node 10 is selected for simulation
The node 2 is selected for simulation
>>
Here in the output i got 1,7 repeated. I used 'shuffle ' to avoid the duplication still in the result some duplication occur. How can i avoid this problem. Can anyone suggest me some hint to sort this problem? Thank you
댓글 수: 0
답변 (1개)
Walter Roberson
2021년 10월 25일
node_sequence = randperm(n, t-reply_timer);
Now use the elements of node_sequence, in that order.
You will quickly get an error if reply_timer is generated as 1, 2, 3, or 4. That is because it is impossible to generate 11 or more different numbers in the range 1 to 10 (n)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!