I want to fill an array with random values. The code I wrote is this one:
public class PersonalityMap
{
const int size = 16;
byte[,] fullMap = new byte[size, size];
/// <summary>
/// Generates a random map
/// </summary>
public PersonalityMap()
{
Random random = new Random();
byte[] row = new byte[size];
for (int i = 0; i < size; i++)
{
random.NextBytes(row);
for (int j = 0; j < size; j++)
fullMap[i, j] = row[j];
}
}
}
But I feel there's a way to do it faster.
The java. util. Random. nextBytes() method generates random bytes and provides it to the user defined byte array.
rand(): rand() function is a predefined method of C++. It is declared in <stdlib. h> header file. rand() is used to generate random number within a range.
Fills the elements of a specified array of bytes with random numbers. Fills the elements of a specified span of bytes with random numbers.
Well, you could create one single-dimensional array, fill that, and then copy it with Buffer.BlockCopy:
Random random = new Random();
byte[] row = new byte[size * size];
random.NextBytes(row);
Buffer.BlockCopy(row, 0, fullMap, 0, size * size);
However, before you try to optimize even further - just how quick do you need this to be? Have you benchmarked your application and determined that this is the bottleneck of your application?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With