Most tip calculator apps simply take a flat percentage of the meal price. So, for example, if your meal is $23.45, you can leave a 15% tip = $3.52, or a more generous 20% tip = $4.69.
Convenient enough for credit card users. But not so if you prefer to leave cash tips, in which case these oddball cent amounts get in the way. So let's modify the idea to be more convenient for cash users.
Your assignment
Write, in as few bytes as possible, a program or function that takes as input:
- Price of the meal
- Minimum tip percentage
- Maximum tip percentage
And output any tip amount within the range [price * min_percentage / 100, price * max_percentage / 100] that minimizes the number of bills/banknotes and coins required.
Assume the US monetary denominations of 1¢, 5¢, 10¢, 25¢, $1, $5, $10, $20, $50, and $100.
Example
Here is a non-golfed example program in Python:
import math
import sys
# Do the math in cents so we can use integer arithmetic
DENOMINATIONS = [10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1]
def count_bills_and_coins(amount_cents):
# Use the Greedy method, which works on this set of denominations.
result = 0
for denomination in DENOMINATIONS:
num_coins, amount_cents = divmod(amount_cents, denomination)
result += num_coins
return result
def optimize_tip(meal_price, min_tip_percent, max_tip_percent):
min_tip_cents = int(math.ceil(meal_price * min_tip_percent))
max_tip_cents = int(math.floor(meal_price * max_tip_percent))
best_tip_cents = None
best_coins = float('inf')
for tip_cents in range(min_tip_cents, max_tip_cents + 1):
num_coins = count_bills_and_coins(tip_cents)
if num_coins < best_coins:
best_tip_cents = tip_cents
best_coins = num_coins
return best_tip_cents / 100.0
# Get inputs from command-line
meal_price = float(sys.argv[1])
min_tip_percent = float(sys.argv[2])
max_tip_percent = float(sys.argv[3])
print('{:.2f}'.format(optimize_tip(meal_price, min_tip_percent, max_tip_percent)))
Some sample input and output:
~$ python tipcalc.py 23.45 15 20
4.00
~$ python tipcalc.py 23.45 15 17
3.55
~$ python tipcalc.py 59.99 15 25
10.00
~$ python tipcalc.py 8.00 13 20
1.05
a program that takes as input (stdin, command-line arguments, or GUI input box, whichever is most convenient in your language)
Is this intended to override our defaults for inputs and outputs? That is, would e.g. a function that takes three numbers and returns the result be allowed? \$\endgroup\$3.51
and3.75
are also valid outputs for the test case23.45 15 17
? They use the same amount of coins and are also inside the range. \$\endgroup\$