Start learning free

LESSON 652 OF 671 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Shipping Options

Practice O(1)

An online shop offers three ways to ship a parcel. Standard shipping is the basic one. Express and Economy are kinds of shipping too: they answer the same two questions, what the option is called and what it costs, but each in its own way. As in the lesson Method Overriding, Express and Economy embed Shipping and give themselves methods with the same names, which shadow the embedded ones.

Write the struct Shipping, the standard option (it has no fields):

  • name() returns "Standard".
  • cost(weight) returns 5 + weight: a base price of 5, plus 1 for each kilogram.

and two structs that embed Shipping and have their own name and cost:

  • Express: name() returns "Express", and cost(weight) returns 10 + 2*weight.
  • Economy: name() returns "Economy", and cost(weight) returns 3 + weight/2, where the division rounds down: 7/2 is 3.

The input lists parcels, one per line: the option (standard, express or economy) and the weight. For each line, the code that tests your structs creates a value of that type (Shipping{}, Express{} or Economy{}) and prints <name>: <cost> from its name() and cost(weight). On an Express value, name() runs Express's own method, not the embedded Shipping's.

 

Example 1:

Input:
    standard 4
    express 4
    economy 4
Output:
    Standard: 9
    Express: 18
    Economy: 5
Explanation: The same parcel of 4 kilograms costs 5 + 4 = 9 with Standard, 10 + 2*4 = 18 with Express
and 3 + 4/2 = 5 with Economy.

Example 2:

Input:
    standard 0
    express 0
    economy 0
Output:
    Standard: 5
    Express: 10
    Economy: 3
Explanation: With a weight of 0, only the base prices are left.

Example 3:

Input:
    economy 7
    economy 1
    standard 7
    express 7
Output:
    Economy: 6
    Economy: 3
    Standard: 12
    Express: 24
Explanation: Economy halves the weight and rounds down: 7/2 is 3, so 3 + 3 = 6, and 1/2 is 0, so 3 + 0 = 3.

 

Constraints:

  • 0 <= weight <= 1000, a whole number of kilograms.
  • At most 100 parcels per test case.
STEP 1 OF 8
    Ctrl + Enter to check