FrogSimulation free response answer

FrogSimulation free response problem from the 2018 AP Computer Science A Exam.

FrogSimulation is #1 from the from the 2018 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/ap/pdf/ap18-frq-computer-science-a.pdf

Part (a) – simulate method

public boolean simulate()
{
  int frogPosition = 0;
  int hopsRemaining = maxHops;

  while(frogPosition < goalDistance &&
      frogPosition >= 0 &&
      hopsRemaining > 0)
  {
    frogPosition += hopDistance();
    hopsRemaining--;
  }

  return frogPosition >= goalDistance;
}

Part (b) – runSimulations method

public double runSimulations(int num)
{
  int successfulRuns = 0;

  for(int run = 1; run <= num; run++)
    if(simulate())
      successfulRuns++;

  return successfulRuns / (double) num;
}

Leave a Reply