Efficiently generating unique pairs of integers

前端 未结 3 1335
鱼传尺愫
鱼传尺愫 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:06

    This is more of a general approach rather then a matlab solution.

    How about you do the following first you fill a vector like the following.

    x[n] = rand()
    x[n + 1] = x[n] + rand() %% where rand can be equal to 0.
    

    Then you do the following again

    x[n][y] = x[n][y] + rand() + 1
    

    And if

    x[n] == x[n+1]
    

    You would make sure that the same pair is not already selected.

    After you are done you can run a permutation algorithm on the matrix if you want them to be randomly spaced.

    This approach will give you all the possibility or 2 integer pairs, and it runs in O(n) where n is the height of the matrix.

提交回复
热议问题