gpt4 book ai didi

javascript - 给定数量要使用的最少硬币数量

转载 作者:行者123 更新时间:2023-11-30 20:27:31 25 4
gpt4 key购买 nike

我正在尝试在 javascript/jquery 中创建一个函数来计算将最少的硬币数量加起来达到输入的总金额。

所以我有一个硬币对象数组:

var coins = [
{
pennies: 200,
print: '£2'
},
{
pennies: 100,
print: '£1'
},
{
pennies: 50,
print: '50p'
},
{
pennies: 20,
print: '20p'},
{
pennies: 10,
print: '10p'
},
{
pennies: 5,
print: '5p'},
{
pennies: 2,
print: '2p'
},
{
pennies: 1,
print: '1p'
}
];
var $input = $('input');
$input.keypress(function(e) {
if (e.which == 13) {
// do something
}
});

还有我的 HTML 中的输入字段。

因此,如果有人输入 123p,我希望表单返回 1 x £1、1 x 20p、1 x 2p 和 1 x 1p。

我正在努力弄清楚从哪里开始。如果有人可以提供帮助,我们将不胜感激。

谢谢

最佳答案

听起来您只需要从最高面额开始遍历 coins 数组:

const coins=[{pennies:200,print:'£2'},{pennies:100,print:'£1'},{pennies:50,print:'50p'},{pennies:20,print:'20p'},{pennies:10,print:'10p'},{pennies:5,print:'5p'},{pennies:2,print:'2p'},{pennies:1,print:'1p'}];

const getCoins = penniesToGo => coins.reduce((coinCountStr, { pennies, print }) => {
const numCoins = Math.floor(penniesToGo / pennies);
if (numCoins < 1) return coinCountStr;
penniesToGo -= numCoins * pennies;
const thisCoinStr = `${numCoins}x ${print}`;
return coinCountStr ? coinCountStr + ', ' + thisCoinStr : thisCoinStr;
}, '');

console.log(getCoins(201));
console.log(getCoins(333));
console.log(getCoins(6));

关于javascript - 给定数量要使用的最少硬币数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50730877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com