2

I have a byte array with 10 bytes. I want to create an array of bytes 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 bytes size using the above bytes.

4
  • Please, give example what code do you have and examples byte array what you have and what you want to get. Commented Dec 9, 2015 at 0:05
  • @Viacheslav Vedenin edited Commented Dec 9, 2015 at 0:08
  • What do you mean by frequency? Commented Dec 9, 2015 at 3:20
  • @JayC667 how many times each byte appears Commented Dec 9, 2015 at 8:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.