The BatteryCharger
problem from the 2009 AP Computer Science Exam is typical of free response problems that test arrays.
BatteryCharger
is #3 from the 2009 AP Computer Science Free Response.
https://secure-media.collegeboard.org/apc/ap09_frq_computer_science_a.pdf
Part (a) getChargingCost
method
private int getChargingCost(int startHour, int chargeTime)
{
int cost = 0;
for(int hour = startHour; hour < startHour + chargeTime; hour++)
cost += rateTable[hour % rateTable.length];
return cost;
}
Division operations includes a discussion of modular division, including using it to constrain a value.
Part (a) getChargingCost
method (alternate solution 1)
private int getChargingCost(int startHour, int chargeTime)
{
int cost = 0;
int rIndex = startHour;
int hoursRemaining = chargeTime;
while(hoursRemaining > 0)
{
cost += rateTable[rIndex];
rIndex++;
if(rIndex == rateTable.length)
rIndex = 0;
hoursRemaining--;
}
return cost;
}
Many students have indicated that it would not have occurred to them to use the mod operator (%
) from my solution. An easy alternative is to track the index for rateTable
separately from the hours remaining.
Part (a) getChargingCost
method (alternate solution 2)
private int getChargingCost(int startHour, int chargeTime)
{
int cost = 0;
int rIndex = startHour;
for(int h = 1; h <= chargeTime; h++)
{
cost += rateTable[rIndex];
rIndex++;
if(rIndex == rateTable.length)
rIndex = 0;
}
return cost;
}
This is the same as alternate solution 1 except with a for loop instead of a while loop. I prefer to use a for loop whenever I know the start and end (which I do here).
Part (b) getChargeStartTime
method
public int getChargeStartTime(int chargeTime)
{
int cheapestStartHour = 0;
for(int startHour = 1; startHour < rateTable.length; startHour++)
if(getChargingCost(startHour, chargeTime) <
getChargingCost(cheapestStartHour, chargeTime))
cheapestStartHour = startHour;
return cheapestStartHour;
}
This is a standard find the min problem that should be solved using the standard algorithm. The method returns the start hour that results in the lowest cost, so we store the cheapest start hour so far.
2009 AP CS Exam Free Response Solutions
- NumberCube Free Response Solution
- StockpileCritter Free Response Solution
- TileGame Free Response Solution
Help & comments
Get help from AP CS Tutor Brandon Horn