Search code examples
algorithmrandombinarylanguage-agnosticbitwise-operators

Binary random number with a specific number of ones


I am looking to randomly insert ones into a binary number where each specific set of bits has a fixed number of ones. For example, if I have a 15 bit number, all 3 sets of 5 bits must have exactly 3 ones each. I need to generate say, 40 such unique binary numbers.

import numpy as np
N = 15
K = 9 # K zeros, N-K ones
arr = np.array([0] * K + [1] * (N-K))
np.random.shuffle(arr)

This is something that I discovered, but the issue is, here, this solution means that it is not necessary that the ones are distributed in the way that I want - through this solution, all ones can be grouped together right at the beginning, such that the last set of 5 bits are all zeroes - and this is not what I'm looking for.

Also, this method does not guarantee that all combinations I have are unique.

Looking for any suggestions regarding this. Thank you!


Solution

  • If I understand the question correctly, you could do something like this in Python:

    import random
    
    def valgen():
        set_bits = [
            *random.sample(range(0, 5), 3),
            *random.sample(range(5, 10), 3),
            *random.sample(range(10, 15), 3),
        ]
        return sum(1<<i for i in set_bits)
    

    i.e. sample three sets of integer values, without replacement, in each block and set those bits in the result.

    if you want 40 unique values, I'd do:

    vals = {valgen() for _ in range(40)}
    while len(vals) < 40:
        vals.add(valgen())
    

    see the birthday problem for why you should expect approx one duplicate per set of 40