2

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Shehryar Farooq
  • 115
  • 3
  • 13

4 Answers4

7

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.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51
4

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.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Thankyou, I have made the array, now I just have to generate a random numbber from [0,11] , do you know exactly how I can do that? I am not familiar with random number generation in c++ – Shehryar Farooq Dec 01 '11 at 14:07
  • @Shehryar This should be an exercise left for the reader. This is easy enough to look up in pretty much every reference manual. – Manny D Dec 01 '11 at 14:10
  • 1
    @ShehryarFarooq: Make sure your answer isn't `rand() % 12`, which doesn't do what you asked! – Kerrek SB Dec 01 '11 at 14:51
1

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 ]

znarf
  • 814
  • 2
  • 15
  • 31
0

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.

Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65