Draw between user-defined options

Asked

Viewed 442 times

0

Hello, I am creating a Petri Net simulator (I considered it a challenge, since I am a beginner) and I would like to know if there is a way to create a draw between user-defined options. I would like to draw between, for example, 0, 2, 3 and 5 (these numbers are positions of an array). The array has the amount of user-defined positions (this has already been provided), and the program will read the positions the user wants. I need the program to draw one of the defined positions and increase the value in the drawn position. I couldn’t do this with the common Rand() because it only draws between a range of numbers, and not between options. There is this possibility?

1 answer

1

The idea is to draw by the amount of elements of your vector and not by the numbers that are there. Imagining that you have a vector with [45,3,40,12,2] must draw lots of 0 to 4, which are vector positions and not 2 to 45 that would be the numbers.

If the numbers you want to draw are houses in an array, it won’t matter either. Build a new array with these numbers (houses) and draw the draw from there. In your case could consider as available numbers:

int disponiveis[] = {0,2,3,5};

And draw on this array, and the rest of the logic would apply equally.

Simple draw without quantity

srand (time(NULL)); //inicializar a semente randomica

int nums[4] = {0 , 2, 3 ,5};
int posicaoSorteada = rand() % 4; //gerar um numero de 0 a 4

//mostrar o elemento na posição sorteada
std::cout<<"Elemento sorteado "<<nums[posicaoSorteada];

See this example in Ideone

Notice how the draw was made by the positions and not by the numbers themselves.


Draw with quantity

If you need to know how many times an element has been drawn you can turn the vector into a two-dimensional array and each time you draw the quantity in the second dimension.

This way it is as if it had in the first column the number and in the second column the amount of times it has already left.

srand (time(NULL));

//agora com duas dimensões, e a 2 dimensão começa a 0 para todos, que é a quantidade
int nums[4][2] = {{0,0} ,{2,0},{3,0},{5,0}};

int sorteios = 30; //sortear 30 elementos

while (sorteios-- > 0){
    int posicaoSorteada = rand() % 4;
    nums[posicaoSorteada][1]++; //aumenta a quantidade do numero sorteado, coluna 1
    std::cout<<"Elemento sorteado "<<nums[posicaoSorteada][0]<<" ja saiu "
    <<nums[posicaoSorteada][1]<<" vezes"<<endl;
}

See this example also in Ideone

Notice how in this last example nums[..][0] refers to the number while nums[..][1] refers to the quantity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.