This is a different question from the one I just asked and it is more challenging.
I have an unsigned char array, say unsigned char A[16]. I need to generate a mask vector which i will apply to my array A[16].
It should contain n number of '1's, where 0 < n < 16*8 (The mask vector can be an array B[16] as long as there are n number of '1's in the array)
I also need these n number of '1's distributed randomly in the vector.
How can I do this in c/c++?
Thank you!
Edit: My thought is as follows: I will generate n random numbers (checking needs to be done to make sure all n numbers are not the same) and store them in array tmp[n]. Then mask is generated based on shifting.
srand(time(0));
for(i = 0; i < n; i++){
for(j = 0; j < i; j++)
while(tmp[i] == tmp[j]) // to make sure all n random numbers are different
tmp[i] = rand()%128;
unsigned char mask[16]
for(i = 0; i < n; i++)
mask[16] |= (1 << tmp[i]); //generate mask
You have an array of 16
unsigned char
s, which can be seen as 16 * 8 bits. To generate a random mask withn
1 bits in it, generate a random position in the range [0, 16*8) and set the corresponding bit to 1. If the bit was previously zero, then you have just added a bit to the array. Repeat this until you have addedn
bits.Generate random
(i,j)
pair of numbers, wherei < 16
andj < 8
. If the bit at positionB[i]&(1<<j)
is not set, set it and increment "count". Loop until "count" reaches "n".A bit of code (untested):
Exercise, for the challenge: remove magic constant
16
from the code.Edit: The modification suggested in your comments contains a nasty bug. Here is a test program to play with the way bits are distributed in your output mask.
When this program is run, it will try every value of
n
from0
to16*8
and generate a random mask withn
bits, then verify that exactlyn
bits are set. If any error occurs (for some value ofn
, somek!=n
bits are set), a message is output.If I change the condition to
if ( (B[i]^mask) != 0 )
, I get consistent errors in the output. Every run produces at least 1 error message. The original conditionif ( (B[i]&mask) == 0 )
consistently produces 0 error messages.