Frog Simulation Solution

For this FRQ you are 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 he starts.

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

I used a while loop that continued as long as the frog still has hops remaining, has not passed the goal distance, and hasn’t gone backwards. Each time it loops 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())
  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. Newsletter

Want to stay in touch and keep up to date with the latest posts @

Leave a Reply

Your email address will not be published. Required fields are marked *