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!