It seems you could just take the bit x = ceil (log_2 (n)) at a time, and just use them as your random numbers. The problem you will encounter is that if the number you get is more than your limit (for example, 5), then you will want to do the magic to get it less than 5, but evenly. In this case, it is logical to assume that you just take a few more bits, but since you indicated that we cannot spend bits, then we need to be more creative. I would recommend a right or left turn, but this will not always lead you out of the situation. (Consider a row of 111 when you need n = 5). We could make up x rotate to see if one of the rotations falls into the correct range, or we could just flip all the bits and add 1 (two additions). I believe this will make it homogeneous.
So, for example, if you had the following line (the rightmost bit is the first one you get):
101001111010010101
And you use n = 5, then ceil (log2 (n)) = 3, so you will use three bits at a time, and the following results will be (at each step):
t=0 : 101 = 5 t=1: 010 = 2 t=2: 010 = 2 t=3: 111 = 7 -> too large, rotates won't work, so we use 2 complement: 001 = 1 t=4: 001 = 1 t=5: 101 = 5
jwir3 source share