RandomNumberBucketArray.java

  1. package org.drip.zen.numbers;

  2. public class RandomNumberBucketArray {

  3.     public static double CalculatePercentage (int count, int total)
  4.     {
  5.         double percent = 100. * (double) count / (double) total;
  6.         return percent;
  7.     }

  8.     public static int FindBucketIndex (double number, int totalBuckets)
  9.     {
  10.         int bucketIndex = 0;
  11.         double bucketWidth = 1. / totalBuckets;

  12.         for (int i = 0; i < totalBuckets; i = i + 1) {
  13.             double bucketLeftEnd = i * bucketWidth;
  14.             double bucketRightEnd = (i + 1) * bucketWidth;

  15.             if (number > bucketLeftEnd && number <= bucketRightEnd)
  16.                 bucketIndex = i;
  17.         }

  18.         return bucketIndex;
  19.     }

  20.     public static void main (String[] args)
  21.     {
  22.         int numberOfBuckets = 10;

  23.         int[] countbucket = new int[numberOfBuckets];

  24.         int totalTrials = 10000;
  25.         int trialNumber = 1;

  26.         while (trialNumber <= totalTrials)
  27.         {
  28.             double randomNumber = Math.random();

  29.             int randomNumberBucket = FindBucketIndex (randomNumber, numberOfBuckets);

  30.             countbucket[randomNumberBucket] = countbucket[randomNumberBucket] + 1;

  31.             trialNumber = trialNumber + 1;
  32.         }

  33.         String countString = "\t| ";

  34.         for (int i = 0; i < numberOfBuckets; i = i + 1)
  35.             countString = countString + countbucket[i] + " | ";

  36.         System.out.println (countString);

  37.         String countPercentString = "\t| ";

  38.         for (int i = 0; i < numberOfBuckets; i = i + 1)
  39.             countPercentString = countPercentString + CalculatePercentage (countbucket[i], totalTrials) + "% | ";

  40.         System.out.println (countPercentString);
  41.     }
  42. }