Use a map as a fast lookup table for coupon discounts.
You start with:
val subtotal = 100
val coupon = "SAVE20"
val coupons = mutableMapOf("SAVE10" to 10, "SAVE20" to 20, "SAVE50" to 50)
Build:
Total: $80
Rules:
- Look up
couponincoupons. If it is there, its value is thediscount; if it is not (an unknown code), the discount is0. total = subtotal - discount.- Build the text
"Total: $<total>"(e.g."Total: $80"; an unknown coupon would give"Total: $100"). - Store it in
result, then print it withprintln(result).
Use
coupons.getOrDefault(coupon, 0): it returns the value if the key is present, or 0 if it is missing.
In Kotlin
"Total: $" + total converts the number to text for you.
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)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
