Re: can this code be improved
import java.util.ArrayList;
import java.util.Random;
public class SixFourNine {
ArrayList winningNumbers = null;
public static int NUM_CHOICES = 6;
public static int MAX_NUMBER = 49;
int[][] simulationArray = new int[MAX_NUMBER][2];
/** creates a new SixFourNine object**/
public SixFourNine() {
initializeSimulationArray();
}
/** initializes the array for storing the simulation **/
public void initializeSimulationArray() {
for (int i=0; i <MAX_NUMBER; i++) {
simulationArray[i][0] = (i+1);
simulationArray[i][1] = 0;
}
}
/** default simulation -- 1 million trials **/
public void runSimulation() {
runSimulation(1000000);
}
/** simulation -- specify # trials **/
public void runSimulation(int numTrials) {
if (numTrials <= 0 ) return;
Random rand = null;
int number = 0;
for (int i = 0; i < numTrials; i++ ){
rand = new Random() ;
number=rand.nextInt(MAX_NUMBER) + 1;
simulationArray[number-1][1]++;
}
}
/** get the winning numbers. throws an exception if you have not
run a simulation **/
public ArrayList getWinningNumbers() throws
SixFourNineSimulationNotRunException {
if (simulationArray == null) throw new
SixFourNineSimulationNotRunException();
winningNumbers = new ArrayList();
for (int i = 0; i < NUM_CHOICES; i++) {
Integer r = new Integer(findAndRemoveMax());
winningNumbers.add(r);
}
initializeSimulationArray();
return winningNumbers /*NOT A GUARANTEE*/;
}
/** finds the most picked number from the simulations, in the case
of a tie, largest number (index) wins **/
private int findAndRemoveMax() {
int max = 0;
int count = 0;
for (int i = 0; i < MAX_NUMBER; i++) {
if (simulationArray[i][1] > count) {
count = simulationArray[i][1] ;
max = i;
}
}
simulationArray[max][1] =0;
return max+1;
}
/** program main **/
public static void main(String[] args) {
SixFourNine sfn = new SixFourNine();
sfn.runSimulation(1000000);
try {
System.out.println(sfn.getWinningNumbers());
} catch (SixFourNineSimulationNotRunException sfnnre) { // this
cannot happen in this example but we must catch;
System.out.println("Sorry, there was a problem; you need to
run a simulation before you can guess the winning numbers!");
System.exit(42);
}
System.exit(0);
}
public class SixFourNineSimulationNotRunException extends Exception
{};
}