Efficiently generating unique pairs of integers

前端 未结 3 1344
鱼传尺愫
鱼传尺愫 2020-12-30 06:45

In MATLAB, I would like to generate n pairs of random integers in the range [1, m], where each pair is unique. For uniqueness, I consider the order

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 07:01

    The following code does what you need:

    n = 10000;
    m = 500;
    my_list = unique(sort(round(rand(n,2)*m),2),'rows');
    my_list = my_list(find((my_list(:,1)==my_list(:,2))==0),:);
    %temp = my_list;    %In case you want to check what you initially generated.
    while(size(my_list,1)~=n)
        %my_list = unique([my_list;sort(round(rand(1,2)*m),2)],'rows');
        %Changed as per @jucestain's suggestion.
        my_list = unique([my_list;sort(round(rand((n-size(my_list,1)),2)*m),2)],'rows');
        my_list = my_list(find((my_list(:,1)==my_list(:,2))==0),:);
    end
    

提交回复
热议问题