Start learning free

LESSON 660 OF 679 · 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. Rust has no class inheritance; as in the lesson Method Overriding, the parent's behavior is a trait with default methods, and a type replaces a default by writing its own method in its impl block.

Write the trait Shipping, whose default methods are the standard option:

  • name(&self) -> &str returns "Standard".
  • cost(&self, weight: i32) -> i32 returns 5 + weight: a base price of 5, plus 1 for each kilogram.

Standard implements Shipping with an empty block, impl Shipping for Standard {}, so it keeps both defaults. Then write the two types that replace both methods:

  • Express: name returns "Express", and cost returns 10 + 2 * weight.
  • Economy: name returns "Economy", and cost 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 types creates that option, keeps it as a Box<dyn Shipping>, and prints <name>: <cost> from its name() and cost(weight). The calls are the same for every option; each type answers with its own method, or with the trait's default where it has none.

 

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 6
    Ctrl + Enter to check