简体   繁体   中英

Randomly Generating a 2d/3d Array

I've thought about this for awhile but what is maybe a good way to go about randomly generating a 2-d or possibly 3-d array. Im not looking for specific code per se, but more just a general idea or way one might think of doing it.

edit: Sorry I mistyped, What I meant is say you have an array (2d or 3d) filled with empty space, and I wanted to randomly generate Char *'s in it......randomly(everything else would be blank). is what I meant.

  1. create a 2D/3D array
  2. Fill it with random data
  3. ?????
  4. Profit!

只需使用rand()生成一堆随机值并将它们排列成一个数组。

如果您希望随机性在2或3维上具有连续性,那么您要寻找的概念是“噪声”。

I know you didn't want the whole code, but it's really not that much code.

int array[A][B][C];
std::generate_n(array[0][0], A*B*C, rand);

This should work:

int *ary,   /* Array */
    x_size, /* X size of the array */
    y_size; /* Y size of the array */

x = rand() % MAX_SIZE;
y = rand() % MAX_SIZE;

ary = malloc(sizeof(int) * (x * y));

ary[1][1] = 1;

If the [][] indexing doesn't work, you may need to use

*(ary + (x_size * X_COORD) + Y_COORD)

to access element [X_COORD][Y_COORD] . I'm not completely sure whether c99 supports that syntax.

Sorry, I couldn't think of a way to say it without code.

EDIT: Sorry for the confusion - thought you needed a random size array.

If you were trying to sparsely fill a large 2D array with uppercase ASCII characters it would be something like the following in C:

int array[A][B];

for (int i = 0; i < SOMETHING; ++i)
{
          //Note: Modulus will not give perfect random distributions depending on 
          //the values of A/B but will be good enough for some purposes.
     int x = rand() % A;  
     int y = rand() % B;

     char ch = rand() % 26 + 'A';
     array[x][y] = ch;
}

This is not the exact answer you asked for, but could prove useful anyway. Sometimes when I want to generate a large random string, I do the following: 1. generate a small random string, say 3 or 4 characters in length 2. get its hash with your algorithm of choice (MD5, SHA1, etc)

In this way you can generate quite long 'randoms' strings. Once you have the very long random string you can split it up into smaller ones or use it whole. The integrity of the randomness is based on how random the short initial string is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM