@lucadani7/algonodejs-for-beginners
Version:
Just a simple Node.js package with some basic algorithms perfect for people just starting out. It's got easy-to-understand TypeScript versions of stuff like sorting, searching, math with numbers, and messing with strings.
43 lines (42 loc) • 1.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SumPayment = void 0;
const SortingAlgorithms_1 = require("./SortingAlgorithms");
class SumPayment {
static sortArrayDesc(arr) {
SortingAlgorithms_1.SortingAlgorithms.mergeSort(arr, 0, arr.length - 1);
for (let i = 0, j = arr.length - 1; i < j; ++i, --j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
static getPaymentBreakdown(sum, coins) {
this.sortArrayDesc(coins);
const breakdown = [];
let remaining = sum;
for (const coin of coins) {
if (coin <= remaining) {
const count = Math.floor(remaining / coin);
breakdown.push({ coin, count });
remaining -= count * coin;
remaining = parseFloat(remaining.toFixed(10));
}
}
return remaining === 0 ? breakdown : [];
}
static printHowToPayACertainSum(sum, coins) {
const breakdown = this.getPaymentBreakdown(sum, coins);
if (breakdown.length === 0) {
console.log(`Cannot pay ${sum} euro exactly with available coins.`);
return;
}
for (const { coin, count } of breakdown) {
console.log(`We can use ${count} coin${count > 1 ? "s" : ""} of ${coin} euro`);
}
const total = breakdown.reduce((acc, item) => acc + item.count, 0);
console.log(`We used a total of ${total} coins.`);
}
static canPayExactly(sum, coins) {
return this.getPaymentBreakdown(sum, coins).length > 0;
}
}
exports.SumPayment = SumPayment;