Números generados aleatoriamente en C++
Frecuentes
Visto 561 veces
-4
I'm busy with a game and need to place a number into a 2D array at random places on the array. How can I do that?
He
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
array[1 + rand() % row][1 + rand() % col] == 5;
}
}
My program crashes when I run it. What could the problem be?
2 Respuestas
3
As said in the comments, arrays are zero-based so you have generate numbers in the range [0,n-1]
.
Also, you're comparing instead of assigning (note the ==
)
Also, use more modern random generators, they're not only better in the sense of producing correct distributions, but also a lot more easy to use (no more arithmetic fiddling). For example, with C++11's random, you would have the following (this can also be achieved with empujón for pre-c++03):
std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<> disRows(0, rows-1);
std::uniform_int_distribution<> disCOls(0, cols-1);
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
array[disRows(gen)][disCols(gen)] = 5;
}
}
Also, the double loop doesn't make much sense here, if you want to randomly assign 5 'N' times, just loop from 0
a N
(N
podría ser rows*cols
)
contestado el 03 de mayo de 12 a las 20:05
1
array[1 + rand() % row][1 + rand() % col]
is incorrect because the first element is at position 0, not 1.
Trata array[rand() % row][ rand() % col]
EDIT:
rand() % n
returns numbers from 0
a n-1
. In your case adding 1 make it possible to try to access the element at position row
or col
, which are not valid indexes. And even if you wrote
array[1 + rand() % (row-1)][1 + rand() % (col-1)]
It is not truly random as both the first row and the first column will never be touched.
contestado el 03 de mayo de 12 a las 20:05
the question is how do you place the value 5 at random places in the array. - jonathan geers
if rand() % row
retorno row-1
luego 1 + rand() % row
is row
, which is out of bound. - UmNyobe
Yes i got that and it does not give me errors now it does not display the 5 in the array - jonathan geers
@JonathanGeers: see my answer or read the third comment on your question, you use ==
en lugar de =
- KillianDS
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c++ random multidimensional-array or haz tu propia pregunta.
Muestre la declaración de
array
. - ildjarnArrays are 0-based, not 1-based. - Mark Ransom
Además, estás usando
==
and not assignment=
was this just a typo, or is this your real code? - Chris A.and the assignment is iterated rows*cols times, so you will end up with a matrix with random number of 5s. - guinny
These loops don't make sense, you don't even use
i
yj
(for each cell you pick another random cell) - Alink