FRQ 1 - Methods and Control Structures
Frog Simulation
public class FrogSimulation
{
/** Distance, in inches, from the starting position to the goal. */
private int goalDistance;
/** Maximum number of hops allowed to reach the goal. */
private int maxHops;
/** Constructs a FrogSimulation where dist is the distance, in inches, from the starting
* position to the goal, and numHops is the maximum number of hops allowed to reach the goal.
* Precondition: dist > 0; numHops > 0 */
public FrogSimulation(int dist, int numHops)
{
goalDistance = dist;
maxHops = numHops;
}
/** Returns an integer representing the distance, in inches, to be moved when the frog hops.
Implemented here to test
*/
private int hopDistance()
{
//Max value of 20, minimum value of - 10;
int randHop = (int)(Math.random() * 30) - 10;
return randHop;
}
/** Simulates a frog attempting to reach the goal
* Returns true if the frog successfully reached or passed the goal during the simulation; * false otherwise.
*/
public boolean simulate()
{
int current = 0;
for(int i=0; i<maxHops; i++){
current += hopDistance();
//sets the current distance to the added value of hopDistance through each increment
if(current < 0){
return false;
//if the position becomes negative, immediately ends
}else if(current >= goalDistance){
return true;
}
}
return false;
//if never reaches current after max hops, false
}
/** Runs num simulations and returns the proportion of simulations in which the frog
* successfully reached or passed the goal.
* Precondition: num > 0 */
public double runSimulations(int num)
{
int success = 0;
//sets initial success to 0
for(int runs = 0; runs < num; runs++){
if(simulate() == true){
//runs through the input num of runs, if simulate is true then increase success
success++;
}
}
return (double) success/num;
//cast success as a double
}
}
public class FrogSimulationTester
{
public static void main(String[] args)
{
FrogSimulation phrog = new FrogSimulation(24,5);
FrogSimulation phrog2 = new FrogSimulation(100,5);
FrogSimulation phrog3 = new FrogSimulation(5,5);
//creates 3 new frogs to test different situations
System.out.println("Part A:");
System.out.println("Running simulation:");
System.out.println(phrog.simulate());
System.out.println(phrog2.simulate());
System.out.println(phrog3.simulate());
//simulates hopping for frogs
System.out.println("---------------------");
System.out.println("Testing Part B:");
System.out.println("Running simulations ratio:");
System.out.println(phrog.runSimulations(400));
System.out.println(phrog2.runSimulations(400));
System.out.println(phrog3.runSimulations(400));
//returns the ratio of successful simulations
}
}
FrogSimulationTester.main(null);