Problem overview
This version applies a coupon to an order. The program starts with a subtotal of 100, the coupon the shopper typed, "SAVE20", and a map coupons from each valid code to the amount it takes off: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50.
The program looks the typed code up in the map. If the code is there, its value is the discount. If it isn't, the discount is 0. The total is the subtotal minus the discount, printed as a single line. For the starting values:
Total: $80
With a code the map doesn't know, such as SAVE99, the same program prints Total: $100: the shopper typed something, and it simply takes nothing off.
Approach: a map as a lookup table
You could answer "which discount does this code give?" with a chain of if statements, one per code. That works for three coupons and gets unwieldy for three hundred, and every new coupon means new code. A map keeps the data separate from the logic: the codes and amounts live in one place, and the lookup is a single call that doesn't change when the table grows.
The one subtle part is the missing key. A shopper can type any text, so the lookup has to have a plan for codes that aren't in the table. The plan here is a default: ask the map for the code, and say what to use if it isn't found.
Step by step
- Look up the discount. Create
discountwithcoupons.getOrDefault(coupon, 0). The call returns the value stored for the key, or its second argument, 0, when the key is absent. - Compute
total. It is the subtotal minus the discount. With no discount it equals the subtotal. - Build
result. It is the textTotal: $followed by the total. The label is the same for every order, only the number changes. - Print
resultwithprintln.
The solution in Kotlin
val subtotal = 100
val coupon = "SAVE20"
val coupons = mutableMapOf("SAVE10" to 10, "SAVE20" to 20, "SAVE50" to 50)
val discount = coupons.getOrDefault(coupon, 0)
val total = subtotal - discount
val result = "Total: $" + total
println(result)
Kotlin details worth a closer look:
- Building the map.
"SAVE10" to 10creates a pair, andmutableMapOfcollects pairs into aMutableMap<String, Int>. Kotlin infers both types from the pairs. A plainmapOfwould make a read-only view; this lesson's starter uses the mutable one, although the solution never changes it. - Missing keys. The indexing form
coupons[coupon]returnsInt?, which isnullfor a code that isn't in the map. That nullable value can't be used insubtotal - ...until you deal with thenull.getOrDefaultavoids the problem by returning a plainInt. The idiomatic Kotlin alternative iscoupons[coupon] ?: 0, where?:supplies the fallback fornull. - Case matters. Map keys are compared with
equals, so"save20"and"SAVE20"are different keys. The lookup forsave20finds nothing and uses 0. - The dollar sign. In
"Total: $"the$is followed by the closing quote, so it is an ordinary character."Total: $total"would not work here: it would insert the number and drop the dollar sign.
Complexity
A map lookup takes constant time on average, no matter how many coupons the table holds, so applying a coupon is O(1). The table itself takes space proportional to the number of coupons.
Edge cases and common mistakes
- Unknown code. Without a default, the lookup yields
nulland the subtraction doesn't compile. With the default, an unknown code costs the shopper nothing and gives nothing. - Letter case. A shopper typing
save20gets no discount, because the keys are matched exactly. - A discount bigger than the subtotal. The solution only subtracts, so nothing stops the total from going negative.
- Printing the discount instead of the total. The output asks for the total after the coupon, not the amount taken off.
Testing
Change coupon and run again. With SAVE99 the program prints:
Total: $100
With save20, in lowercase, it also prints Total: $100. And with SAVE50 on a subtotal of 30, the program prints:
Total: $-20
That last result shows the gap in the rules: a real shop would cap the discount at the subtotal, but this version doesn't.
