Other 2009 FR Questions FR other years Be Prepared Home
A-3
Part (a)
  /** Determines the total cost to charge the battery starting at the beginning of startHour.
   *  @param startHour the hour at which the charge period begins
   *         Precondition: 0 <= startHour <= 23
   *  @param chargeTime the number of hours the battery needs to be charged
   *         Precondition: chargeTime > 0
   *  @return the total cost to charge the battery
   */
  private int getChargingCost(int startHour, int chargeTime)
  {
    int cost = 0;

    for (int hour = 0; hour < chargeTime; hour++)
      cost += rateTable[(startHour + hour) % 24]; 1

    return cost;
  }
Notes:
  1. Or:
        for (int hour = startHour; hour < startHour + chargeTime; hour++)
          cost += rateTable[hour % 24];
    
    Or (if you forgot about the % operator):
        int hour = startHour;
        for (int count = 0; count < chargeTime; count++)
        {
          cost += rateTable[hour];
          hour++;
          if (hour >= 24)
            hour -= 24;
        }
    

Part (b)
  /** Determines start time to charge the battery at the lowest cost for the given charge time.
   *  @param chargeTime the number of hours the battery needs to be charged
   *         Precondition: chargeTime > 0
   *  @return an optimal start time, with 0 <= returned value <= 23
   */
  public int getChargeStartTime(int chargeTime)
  {
    int bestStartHour = 0;
    int minCost = getChargingCost(0, chargeTime);

    for (int hour = 1; hour < 24; hour++)
    {
      int cost = getChargingCost(hour, chargeTime);
      if (cost < minCost)
      {
        bestStartHour = hour;
        minCost = cost;
      }
    }

    return bestStartHour;
  }

Other 2009 FR Questions | Back to Contents

Copyright © 2009 by Skylight Publishing
support@skylit.com