17 Jan 2012 [ 201 week2 ]

We finished out the examples we started last week. I updated that post with the examples we completed (and I'll try to do the same for future classes).

One piece we covered was how to transform uniformly random numbers in the range [0,1) (such as those obtained by calling Math.random()) to integers from a consecutive set such as {1,2,3}.

The steps we used can be broken down as follows:

double r01 = Math.random(); // Generate in [0,1)
double r03 = 3 * r01;       // Stretch out to [0,3)
double r14 = 1 + r03;       // Shift to [1,4)
int r123 = (int)r14;        // Cast to int, dropping fractional part

// Or all at once:
int r123x = (int)(Math.random() * 3 + 1);