import java.text.DecimalFormat; public class I4 { /** * Returns a uniformly random number in the interval [min,max]. * * @param min the lower bound * @param max the upper bound * @throws IllegalArgumentException if min > max * @return the return number */ public static int randomInRange(int min, int max) { if( min > max ){ throw new IllegalArgumentException(); } final int result = min + (int)(Math.random() * (max-min+1)); assert min <= result && result <= max; return result; } /** * Runs randomInRange a given number of times and creates a table with * frequencies of occurrence for each number in the given interval. * This method has no side-effects. * * @return the table */ public static String makeTable(int MIN, int MAX, int CALLS) { int[] a = new int[MAX-MIN+1]; // call the function many times for(int i = 0 ; i < CALLS ; i++){ a[randomInRange(MIN,MAX)-MIN]++; } DecimalFormat df = new DecimalFormat("#.####"); // create the table StringBuilder table = new StringBuilder(); for(int i = MIN ; i <= MAX ; i++){ double freq = 100.0 * a[i-MIN]/(double)CALLS; table.append(i + ": " + df.format(freq) + "%" + "\n"); } return new String(table); } public static void main(String[] args) { final int MIN = 0; final int MAX = 8; final int CALLS = 100000; final int TABLES = 3; for(int i = 0 ; i < TABLES ; i++) { System.out.println(makeTable(MIN, MAX, CALLS)); } } }