Part A

An electric car that runs on batteries must be periodically recharged for a certain number of hours.

The battery technology in the car requires that the charge time not be interrupted.

The cost for charging is based on the hour(s) during which the charging occurs. A rate table lists the 24 one-hour periods, numbered from 0 to 23, and the corresponding hourly cost for each period. The same rate table is used for each day. Each hourly cost is a positive integer. A sample rate table is given below.

 

A BatteryCharger program below uses a rate table to determine the most economic time to charge a battery.

The rate table is implemented as a 1-dimensional array with 24 elements starting at index 0.

In pseudocode, it would be declared as follows:

DECLARE rateTable: ARRAY[0:23] OF INTEGER

In the program, it has global focus.

The function getChargingCost returns the total cost to charge a battery given the hour at which the charging process will start and the number of hours the battery needs to be charged.

For example, using the rate table given at the beginning of this question, the following table shows the resulting costs of several possible charges.

Note that a charge period consists of consecutive hours that may extend over more than one day.

The function header for getChargingCost is written as:

FUNCTION getChargingCost(startHour:INTEGER, chargeTime:INTEGER) RETURNS INTEGER

Using program code, implement this method.

Use this test bed which already has a stub module which you can update with the proper code.

Part B

Write a function getChargeStartTime that returns the start time that will allow the battery to be charged at minimal cost.

If there is more than one possible start time that produces the minimal cost, any of those start times can be returned.

For example, using the rate table given at the beginning of the question, the following table shows the resulting minimal costs and optimal starting hour of several possible charges.

 

You will need to call the functiongetChargingCost that you solved in Part A in this solution.

getChargeStartTime has a function header in pseudocode as follows:

FUNCTION getChargeStartTime(chargeTime:INTEGER) RETURNS INTEGER

Continue to develop the Test Bed given.

Modulus %

The modulus operator will help you to solve part A of this problem.


Video Solutions

Remember, these solutions are here to support you. Make sure you attempt each question first.

Also, remmeber to talk to your teacher or classmates if any of the solutions don't make sense!

Part A

Part B