Reputation: 115
I need a little help with my tetris game that I am coding in C++ , here is my problem:
The list of tetris blocks are 7 types: {'I', 'J', 'L', 'S', 'Z', 'O', 'T'}
and i need to pick ONE of the above character such that S and Z are selected with probability 1/12 each, and the other blocks are selected with probability 1/6 each.
What is my best way to generate the blocks according to these probabilities?
Upvotes: 2
Views: 683
Reputation: 19635
The easiest solution I can think of is to use numeric ranges and pseudo-random numbers.
So, first assign ranges to each letter:
I: 0 to 1
J: 1 to 2
L: 2 to 3
S: 3 to 3.5
Z: 3.5 to 4
O: 4 to 5
T: 5 to 6
then generate pseudo-random numbers within the range 0 to 6. Whichever part of the range that the number falls within, that's the letter you choose.
Unfortunately I do not know C++ so I cannot provide you with code, but I don't think it should be too difficult to implement.
Upvotes: 0
Reputation: 814
put those characters in a character array and generate random values from 0 to 6 with srand()
than you can get a random
char myArray[] = {'I', 'J', 'L', 'S', 'Z', 'O', 'T'};
and then get values with
myArray[ (rand()%5)+1 ]
Upvotes: 1
Reputation: 76848
Create an array like so:
const char* block_distribution = {'I', 'I', 'J', 'J', 'L', 'L', 'S',
'Z', 'O', 'O', 'T', 'T'};
Then pick one element from that array using a uniform distribution.
Upvotes: 4
Reputation: 17268
Declare and define a twelve-item array with a single occurrence of S and Z; two occurrences each of the rest; and pick a random element from that.
Upvotes: 7