Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly initialize BitSet in JAVA

Tags:

java

random

I have BitSet which has to be initialized randomly. Is there any method to do that?

Thanks in advance.

like image 250
user Avatar asked Dec 19 '11 06:12

user


2 Answers

Just go through BitSet and call nextBoolean() of the Random class.

like image 90
Fedor Skrynnikov Avatar answered Sep 26 '22 13:09

Fedor Skrynnikov


If you are using Java 7, you can initialize a random byte array with Random.nextBytes(byte[]) then use the static BitSet.valueOf(byte[]) method to create a BitSet from the same byte array.

Random rnd = new Random();
// ...
byte[] randomBytes = new byte[NUM_BYTES];
rnd.nextBytes(randomBytes);
return BitSet.valueOf(randomBytes);

Or if you want the proportion of 0 vs. 1 bits to be something other than 50:50, check out an old SO question of mine.

like image 27
finnw Avatar answered Sep 24 '22 13:09

finnw