How can I efficiently select several unique random numbers from 1 to 50, excluding x?

后端 未结 5 464
囚心锁ツ
囚心锁ツ 2021-01-06 19:01

I have 2 numbers which are between 0 and 49. Let\'s call them x and y. Now I want to get a couple of other numbers which are not x or y, but are al

5条回答
  •  鱼传尺愫
    2021-01-06 19:36

    You could add x, y and the new number to a data structure that you can use as a set and do something like (in pseudo-code; the set structure needs something like push to add values and in for checking membership):

    number_of_randoms = 2;
    
    set.push(x);
    set.push(y);
    
    for (i = 0; i

    So if objc has something appropriate, this is easy...[aha, it does, see Dave DeLong's post].

    This algorithm makes sense if number_of_randoms is much less than 49; if they are comparable then you should one of the shuffle (aka permutation) ideas.

提交回复
热议问题