Trip
is #1 from the from the 2008 AP Computer Science A Free Response problems.
https://secure-media.collegeboard.org/apc/ap08_comp_sci_a_frq.pdf
Part (a) getDuration
method
public int getDuration()
{
if(flights.size() == 0)
return 0;
return flights.get(0).getDepartureTime().minutesUntil(
flights.get(flights.size() - 1).getArrivalTime());
}
Part (b) getShortestLayover
method
public int getShortestLayover()
{
if(flights.size() < 2)
return -1;
int shortestLayover =
flights.get(0).getArrivalTime().minutesUntil(
flights.get(1).getDepartureTime());
for(int i = 2; i < flights.size(); i++)
{
int layover =
flights.get(i - 1).getArrivalTime().minutesUntil(
flights.get(i).getDepartureTime());
if(layover < shortestLayover)
shortestLayover = layover;
}
return shortestLayover;
}
This is a standard find the min problem. My code above follows my advice at finding the minimum or maximum and starts shortestLayover
at the first value that could be the minimum. The loop starts at 2
, since the first 2 flights have been handled before the loop.
2008 AP CS Exam Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn