import objectdraw.*; import java.util.Random; /** * Generate an array of random numbers and print out statistics * about the numbers. */ public class RandomStats extends FrameWindowController { // Maximum and minimum array size private static final int MAX_SIZE = 20; private static final int MIN_SIZE = 10; // Maximum value of array items private static final int MAX_VAL = 10; private Random rand = new Random(); public void onMousePress(Location point) { // generate a new array of random size int arraySize = rand.nextInt(MAX_SIZE - MIN_SIZE) + MIN_SIZE; System.out.println("Using " + arraySize + " items"); int[] randomNums = new int[arraySize]; // populate the array with random values for (int i = 0; i < randomNums.length; i++) { randomNums[i] = rand.nextInt(MAX_VAL); } // print out the values of the array for (int i = 0; i < randomNums.length; i++) { System.out.println("Item " + i + ": " + randomNums[i]); } // print out statistics about the array System.out.println("Max value is " + getMax(randomNums)); System.out.println("Sum of elements is " + getSum(randomNums)); System.out.println("Mode of values is " + this.getMode(randomNums)); System.out.println(); System.out.println(); System.out.println(); } public int getMax(int[] values) { int max = 0; for (int i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; } } return max; } public int getSum(int[] values) { int sum = 0; for (int i = 0; i < values.length; i++) { sum = sum + values[i]; } return sum; } public int getMode(int[] values) { int mostFrequentValue = 0; int maxOccurrences = 0; // create an array to store the number of occurrences of // each possible array value int[] occurrences = new int[MAX_VAL]; for (int i = 0; i < values.length; i++) { occurrences[values[i]]++; if (occurrences[values[i]] > maxOccurrences) { maxOccurrences = occurrences[values[i]]; mostFrequentValue = values[i]; } } return mostFrequentValue; } }