Javascript的硬币改变/更改决策算法 [英] Javascript Coin changing / Change making algorithm
问题描述
所以,我一直在试图建立在Javascript / jQuery的一个程序,分裂的钱数到美钞的最小量。到目前为止,该项目只与一个法案的作品,我也不太清楚如何实现的休息和需要一推在正确的方向在这里。
VAR票据= [5,10,20,50,100];
而(金钱大于0){//保持deviding
对于(VAR I = 0; I< bills.length;我++){
如果(钱<票据[I])
返回你需要一个$+票据[我] +账单来支付你的项目。
}
}
如果我跑这与金钱= 89;
将返回100,因为这是一个可以支付$ 89最接近的法案,但我希望它回到50 + 20 + 20,它会与金钱= *什么*
。
编辑:在评论我现在已经走了这么远:
而(金钱大于0){//保持deviding
对于(VAR I = bills.length-1; I> = 0; I - ){
如果(钱>票据[I] ||我== 0){
stringToReturn + =+ $+票据[I]
钱 - =账单[I]
打破;
}
}
}
VAR票据= [5,10,20,50,100];
VAR钱= MOD(89);
功能MOD(NUM){
如果(NUM%5 === 0){
返回NUM;
}其他{
返回NUM + 5 - NUM%5
}
}
函数foo(NUM){
VAR指数= bills.length - 1;
变种拆分= [];
而(钱> =账单[0]){
如果(钱> =账单[指数]){
钱 - =账单[指数]
splits.push(票据[指数]);
}其他{
指数 - ;
}
}
返回分割;
}
的console.log(FOO(钱));
So I've been trying to create a program in Javascript/jQuery that splits an amount of money into the smallest amount of dollar bills. So far the program only works with one bill, and I'm not too sure how to implement the rest and need a push in the right direction here.
var bills = [5, 10, 20, 50, 100];
while(money > 0){ // Keep deviding
for(var i=0; i < bills.length; i++){
if(money < bills[i])
return "You need a $" + bills[i] + " bill to pay for your item.";
}
}
If I run this with money = 89;
it will return 100 because that's the closest bill that can pay for $89, but I want it to return 50 + 20 + 20 so it will work with money = *anything*
.
EDIT: After comments I've now come so far:
while(money > 0){ // Keep deviding
for(var i=bills.length-1; i >= 0; i--){
if(money > bills[i] || i == 0){
stringToReturn += " + $" + bills[i];
money -= bills[i];
break;
}
}
}
var bills = [5, 10, 20, 50, 100];
var money = mod(89);
function mod(num){
if (num % 5 === 0){
return num;
}else{
return num + 5 - num % 5
}
}
function foo(num){
var index = bills.length - 1;
var splits = [];
while (money >= bills[0]){
if (money >= bills[index]){
money -= bills[index];
splits.push(bills[index]);
}else{
index--;
}
}
return splits;
}
console.log(foo(money));
edited jsfiddle
这篇关于Javascript的硬币改变/更改决策算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!