## Frog Simulation Solution

For this FRQ you’re implementing two methods inside a `FrogSimulation` class. You are also given a method named `hopDistance()` that returns a random integer for how far a frog hopped.

## Part A

Given a maximum number of hops you’re checking whether the frog is able to get to or past the `goalDistance`. `simulate` should return `true` if the frog reaches or passes `goalDistance` using no more than `maxHops` and never goes backwards from where they start.

``````public boolean simulate() {
int hops = 0;
int cntPos = 0;
while (hops < maxHops && cntPos >= 0 && cntPos < goalDistance) {
cntPos += hopDistance();
hops++;
}
return cntPos >= goalDistance;
}
``````

I used a while loop that continued as long as the frog still had hops remaining, has not passed the goal distance, and hasn’t gone backwards from their starting position. Each time it lops the current position is incremented by `hopDistance()` and the hop is counted.

When it finished if the current position is greater than or equal to the goal distance the method returns `true`. Otherwise it returns `false`.

## Part B

`runSimulation` gives you a set number of times to simulate a frog hop and has you return the percentage of times that the frog was able to successfully reach their goal distance.

``````public double runSimulation(int num) {
int good = 0;
for (int i = 0; i < num; i++) {
if (simulate()) {
good++;
}
}
return (double) good / num;
}
``````

For this I looped `num` times, calling `simulate()` inside each loop. Each time that `simulate()` returned `true` I incremented a counter. At the end it returns the number of successful simulations, cast as a double, divided by the number of tries to get the percentage of good simulations.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.