BatteryCharger free response answer

The BatteryCharger problem from the 2009 AP Computer Science Exam is typical of free response problems that test arrays.

Review the BatteryCharger free response problem with AP CS Tutor Brandon Horn.

BatteryCharger Part (a): getChargingCost

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;
}

BatteryCharger Part (a): getChargingCost – 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.

BatteryCharger Part (a): getChargingCost – 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).

BatteryCharger Part (b): getChargeStartTime

  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;
  }

Get AP CS Help

2009 AP CS Exam Solutions & Explanations

Recommended Practice Problems