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.
- create a 2D/3D array
- Fill it with random data
- ?????
- Profit!
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;
}
Just generate a bunch of random values using rand()
and arrange them into an array.
If you want the randomness to have continuity in 2 or 3 dimensions, the concept you're looking for is "noise".
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 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.
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.
精彩评论