How should I randomly generate pairs of non-identical natural numbers that should also be non-repeating?
8 visualizzazioni (ultimi 30 giorni)
Soudipan Maity il 18 Giu 2019
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.
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 il 18 Giu 2019
[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.