Draw between user-defined options

0

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

    
asked by anonymous 01.10.2017 / 05:26

1 answer

1

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

If the numbers you want to draw are houses in an array, it will also make no difference. Build a new array with these numbers (houses) and draw the lot. In your case you could consider as numbers available:

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

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

No-win simple draw

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 transform the vector into a two-dimensional array, and each time you draw, save the quantity in the second dimension.

In this way it is as if you had in the first column the number and in the second column the number 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 number while nums[..][1] refers to quantity.

    
01.10.2017 / 15:20