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
Generate random
(i,j)pair of numbers, wherei < 16andj < 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
16from 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
nfrom0to16*8and generate a random mask withnbits, then verify that exactlynbits are set. If any error occurs (for some value ofn, somek!=nbits 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.