Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to fill a matrix with Random bytes

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.

like image 835
Jaime Oro Avatar asked Apr 12 '11 19:04

Jaime Oro


People also ask

How do you generate a random byte array?

The java. util. Random. nextBytes() method generates random bytes and provides it to the user defined byte array.

How do you generate random bytes in C++?

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.

What does random nextBytes do?

Fills the elements of a specified array of bytes with random numbers. Fills the elements of a specified span of bytes with random numbers.


1 Answers

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?

like image 96
Jon Skeet Avatar answered Sep 19 '22 18:09

Jon Skeet