Reputation: 11
I have a byte array
with 10
byte
s. I want to create an array
of byte
s with a specific size and it will contain only the specific 10
bytes
randomly but frequency must be almost the same.
I got this:
public static byte[] a = {97, 98, 99, 100, 101, 102, 103, 104, 105, 49, 45};
I want to create a file with binary data that has 2000 byte
s size using the above byte
s.
Upvotes: 2
Views: 1590
Reputation: 424983
The simplest way (from a code perspective) is to make use of Collections.shuffle()
, which shuffles Lists. To use that, you need to create a List
of bytes with the distribution you want.
Here's some code that does that:
byte[] a = {97, 98, 99, 100, 101, 102, 103, 104, 105, 49, 45};
int SIZE_MULTIPLIER = 20;
List<Byte> bytes = new ArrayList<>();
for (byte b : a) for (int i = 0; i < SIZE_MULTIPLIER; i++) bytes.add(b);
Collections.shuffle(bytes);
byte[] random = new byte[SIZE_MULTIPLIER * a.length];
for (int i = 0; i < bytes.size(); i++) random[i] = bytes.get(i);
Note that is matters not how "random" the initial data is - in this case, it's convenient to load element 0 twenty times, then element 1 twenty times, etc.
Because the range of values is not random (each element is used the same number of times as every other element), the distribution of the final array will be identical to the distribution of the initial array.
Upvotes: 2