Most efficient method of generating a random number with a fixed number of bits set

前端 未结 6 1931
清歌不尽
清歌不尽 2020-12-16 03:44

I need to generate a random number, but it needs to be selected from the set of binary numbers with equal numbers of set bits. E.g. choose a random byte value with exactly 2

6条回答
  •  难免孤独
    2020-12-16 04:10

    Here is another option which is very simple and reasonably fast in practice.

    choose a bit at random
    if it is already set
        do nothing
    else
        set it
        increment count
    end if
    

    Repeat until count equals the number of bits you want set.

    This will only be slow when the number of bits you want set (call it k) is more than half the word length (call it N). In that case, use the algorithm to set N - k bits instead and then flip all the bits in the result.

    I bet the expected running time here is pretty good, although I am too lazy/stupid to compute it precisely right now. But I can bound it as less than 2*k... The expected number of flips of a coin to get "heads" is two, and each iteration here has a better than 1/2 chance of succeeding.

提交回复
热议问题