Creating random numbers with no duplicates

后端 未结 18 1813
忘了有多久
忘了有多久 2020-11-21 12:00

In this case, the MAX is only 5, so I could check the duplicates one by one, but how could I do this in a simpler way? For example, what if the MAX has a value of 20? Thanks

18条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 12:05

    The most efficient, basic way to have non-repeating random numbers is explained by this pseudo-code. There is no need to have nested loops or hashed lookups:

    // get 5 unique random numbers, possible values 0 - 19
    // (assume desired number of selections < number of choices)
    
    const int POOL_SIZE = 20;
    const int VAL_COUNT = 5;
    
    declare Array mapping[POOL_SIZE];
    declare Array results[VAL_COUNT];
    
    declare i int;
    declare r int;
    declare max_rand int;
    
    // create mapping array
    for (i=0; i

    Suppose first iteration generated random number 3 to start (from 0 - 19). This would make results[0] = mapping[3], i.e., the value 3. We'd then assign mapping[3] to 19.

    In the next iteration, the random number was 5 (from 0 - 18). This would make results[1] = mapping[5], i.e., the value 5. We'd then assign mapping[5] to 18.

    Now suppose the next iteration chose 3 again (from 0 - 17). results[2] would be assigned the value of mapping[3], but now, this value is not 3, but 19.

    This same protection persists for all numbers, even if you got the same number 5 times in a row. E.g., if the random number generator gave you 0 five times in a row, the results would be: [ 0, 19, 18, 17, 16 ].

    You would never get the same number twice.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题