Skip to content

Instantly share code, notes, and snippets.

@MarcL01
Last active December 31, 2018 00:44
Show Gist options
  • Save MarcL01/1677169308f33a09a26060bda1ef8d50 to your computer and use it in GitHub Desktop.
Save MarcL01/1677169308f33a09a26060bda1ef8d50 to your computer and use it in GitHub Desktop.
import 'dart:io';
void main() {
// printSameFormat(getBills(10.00, 90.00));
while (true) {
print("Enter price: ");
double price = double.tryParse(stdin.readLineSync());
print("Enter tender: ");
double tender = double.tryParse(stdin.readLineSync());
try {
printSameFormat(getBills(price, tender));
} catch (e) {
print(e.toString());
}
}
}
/// The available bills formatted the same way as the price and the tender.
const List<double> bills = [100.00, 50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01];
/// Returns the left over bills from a price and tender.
///
/// Throws a [Exception] if price or tender is null
/// Throws a [Exception] if price is greater than tender.
Map<double, int> getBills(double price, double tender) {
if (price == null || tender == null) {
throw ("Invalid price/tender, please try again");
}
double cashBack = tender - price;
if (cashBack < 0) {
throw ("Thats not enough money! I still need \$" + (cashBack * -1).toStringAsFixed(2) + " more!");
}
Map<double, int> ret = new Map();
bills.forEach((bill) {
int amount;
if ((amount = (cashBack ~/ bill)) > 0) {
cashBack = cashBack % bill;
}
ret.putIfAbsent(bill, () {
return amount;
});
});
return ret;
}
/// Prints the bills and their amounts following the challenges format.
void printSameFormat(Map<double, int> billAmounts) {
billAmounts.forEach((bill, amount) {
if (amount == 1) {
print("$amount bill of \$$bill.");
} else if (amount > 1) {
print("$amount bills of \$$bill.");
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment