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.
You can share your attempt?
– Gabriel Coletta