How should I randomly generate pairs of non-identical natural numbers that should also be non-repeating?

조회 수: 2 (최근 30일)
I want to generate a set of 20 pairs of natural numbers (between a certain range) in which every pair should have two non-identical natural number, and no pair should be repeated in the set under any circumstances.
For example,
Range = 1:10
Formed Data Set of 5 pairs = (2 , 6) ; (5, 4); (1 , 9) ; (2 , 9) ; (5 , 1)
Any help in this regard would be highly appreciated.

채택된 답변

Walter Roberson
Walter Roberson 2019년 6월 18일
[A, B] = ndgrid(range);
mask = A==B;
A(mask) = []; B(mask) = [];
N = length(A);
p = randperm(N, 20);
pairs = [A(p); B(p)].';
The above works well enough when the range is small. When the range gets larger the amount of memory gets larger according to the square of the number of elements in the range. If the number of pairs to be selected grows slower than the number of elements in the range, then at some point it becomes more efficient to use selection with rejection -- select pairs randomly, reject those that do no fit, select additional pairs as needed to reach the number of needed pairs. When the range is small compared to the number of pairs to be selected, that becomes increasingly poor and the non-rejection method I posted becomes better.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by