# C ++, Matrices, random numbers?

3

I am struggling to make a subprocess that fills an array of n x n, with even random numbers, which must be between 1 and 100.

As I understand it, to generate the random numbers I can use the function `rand` , but I do not really know what the functions are. I do not know how to start. I would like to know if someone could help me with the problem.

I update / this is the code that I have been advancing

``````int main()
{
srand(time(NULL));

int matriz ;

for (int fila = 0; fila < 12; fila++)
{
for (int columna = 0; columna < 12; columna++)
{
matriz[fila][columna] = rand() % 256;

cout << matriz[fila][columna] << " ";
}

cout<<endl;
}

cout << "*********************************************************" << endl;

system("pause");
}
``````

and half solved the matrix and the random, but I can not make them just pairs. Greetings and many thanks in advance.

asked by Jose Vargas 29.10.2016 в 06:49
source

4

I can not make them just be even.

If the limitation is to obtain numbers between 0 and 100, it generates numbers from 0 to 50 and multiplies by 2 since any number multiplied by two is even:

``````matriz[fila][columna] = (std::rand() % 50) * 2;
``````

to generate the random numbers I can use the rand function, but I do not really know what the functions are

The functions that generate numbers pseudo-aleatorios have several characteristics that it is necessary to know among which the more important is the type of distribution.

The distribution of the results of `std::rand` is uniform 1 , this means that each of the numbers in the possible range has exactly the same probability of appearing as any other, the range of the results of `std::rand` is between 0 and 2,147,483,647 (2 31 -1).

Given the type of distribution used, it is not advisable to make the return module of `std::rand` to generate random numbers because when used, the probability of some of the numbers in the range is slightly increased (unless it is done module on an exact divisor of 2,147,483,647). In the case at hand, numbers from 0 to 47 will be generated more times than numbers 48 and 49.

To avoid that, it is advisable to use the C ++ 11 random number library:

``````std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 49);

int matriz ;

for (int fila = 0; fila < 12; fila++)
{
for (int columna = 0; columna < 12; columna++)
{
matriz[fila][columna] = dis(gen) * 2;

std::cout << matriz[fila][columna] << ' ';
}

std::cout<<'\n';
}
``````

1 This may vary, check your compiler's documentation.

1

You must use a double loop, in this case two for, to fill the matrix and a "do while" for the restriction to be even

`````` for(int i=0;i<100;i++){
for(int j=0;j<100;j++){
var aux;
do{
aux=rand%100;

}while(aux%2!=0)

matriz[i][j]=aux;

}

}
``````