The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Many Buckets

Of course, as the number of buckets increases, we don't want to have to rewrite the program, especially since the code is getting big and repetitive. Any time you find yourself doing something more than a few times, you should be looking for a way to automate it.

Let's say that we wanted 8 buckets. The width of each bucket would be one eighth of the range, which is 0.125. To count the number of values in each bucket, we need to be able to generate the bounds of each bucket automatically, and we need to have some place to store the 8 counts.

We can solve the first problem with a loop:

    int numBuckets = 8;
    double bucketWidth = 1.0 / numBuckets;

    for (int i = 0; i < numBuckets; i++) {
      double low = i * bucketWidth;
      double high = low + bucketWidth;
      System.out.println (low + " to " + high);

This code uses the loop variable i to multiply by the bucket width, in order to find the low end of each bucket. The output of this loop is:

0.0 to 0.125
0.125 to 0.25
0.25 to 0.375
0.375 to 0.5
0.5 to 0.625
0.625 to 0.75
0.75 to 0.875
0.875 to 1.0

You can confirm that each bucket is the same width, that they don't overlap, and that they cover the whole range from 0.0 to 1.0.

Now we just need a way to store 8 integers, preferably so we can use an index to access each one. Immediately, you should be thinking "array!"

What we want is an array of 8 integers, which we can allocate outside the loop; then, inside the loop, we'll invoke inBucket and store the result:

    int numBuckets = 8;
    int[] buckets = new int [8];
    double bucketWidth = 1.0 / numBuckets;

    for (int i = 0; i<numBuckets; i++) {
      double low = i * bucketWidth;
      double high = low + bucketWidth;
      //System.out.println (low + " to " + high);

      buckets[i] = inBucket (a, low, high);

The tricky thing here is that I am using the loop variable as an index into the buckets array, in addition to using it to compute the range of each bucket.

This code works. I cranked the number of values up to 1000 and divided the range into 8 buckets. The output is:


which is pretty close to 125 in each bucket. At least, it's close enough that I can believe the random number generator is working.

Last Update: 2011-01-24