Design Patterns: Behavioral · Coding problem
Price Shipping With Interchangeable Strategies
A free coding problem from the Strategy Pattern skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Each shipping option is a strategy: its own small class behind the ShippingStrategy interface. Implement the four pricing rules and then a method that finds the cheapest option - using nothing but the interface.
| Strategy | Cost |
|---|---|
standard | 5.00 + 1.50 per kg |
express | 15.00 + 3.00 per kg |
economy | 2.00 + 2.00 per kg |
free100 | 0.00 if the order value is at least 100.00, otherwise 9.99 |
ShippingCalculator.cheapest(weight, value) returns the strategy with the lowest cost; on a tie, the one that appears first in the list wins. Notice that cheapest doesn't care which classes exist - adding a new carrier would be one new class in the list.
In Python: a strategy's name is a class attribute. A one-method strategy is often just a function in Python - the classes keep this one close to the lesson.
Commands: QUOTE <strategy> <kg> <orderValue> and CHEAPEST <kg> <orderValue>.
Example
Input:
3
QUOTE standard 2 40
CHEAPEST 1 40
CHEAPEST 10 40
Output:
standard 8.00
cheapest economy 4.00
cheapest free100 9.99
Constraints
- At most 1000 commands;
0 < kg <= 1000,0 <= orderValue <= 10^6.
How it's graded
- Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Strategy Pattern
Solve it Price Shipping With Interchangeable Strategies free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime