自动售货机没有返回变化

时间:2016-12-28 15:44:21

标签: javascript javascript-objects

这是Code Wars kata:Vending Machine

在这里,我试图模拟自动售货机。到目前为止,如果插入的信用额度不够,我可以退回硬币,我可以让机器告诉我需要多少更改,但我无法让它返回更改。

根据自动售货机拥有的硬币,更改应作为对象返回。

//if this.coins = {1:1, 2:0, 4:3, 6:2}
//and the change needed is 8
//the change should be changeObj = {1: 1, 6: 1}
//the machine is sneaky and can return less than the required amount, but not more.

这里,用于计算更改并返回更改对象的循环按预期工作。



let vmCoins = {1:1, 2:0, 4:3, 6:2}
let changeObj = {}
let changeNeeded = 8

for (let d=changeNeeded; d>0; d--){
	while (vmCoins[d]>0 && (changeNeeded-d)>=0){
  	changeObj[d] ? changeObj[d] ++ : changeObj[d] = 1
    vmCoins[d] --
    changeNeeded -= d
  }
}

console.log(changeObj)




但是当我把它放到主解决方案中时,for循环似乎没有运行。



function VendingMachine(coins){
  this.coins = coins
}

VendingMachine.prototype.vending = function(price,credit){

//Calculate total value of coins inserted
  var changeObj = {}
  let totalCredit =[]
  let arrKeys = Object.keys(credit).map(x=>parseInt(x))
  let arrValues = Object.values(credit)
  for (var i=0; i<arrKeys.length; i++){
  	totalCredit.push(arrKeys[i]*arrValues[i])
  }
  totalCredit = totalCredit.reduce((a,b) => a+b)
  
//if coins inserted less than price, return the inserted coins 
  if (totalCredit<price){
  	return credit
  }
  
//if coins inserted more than item price, put coins into vending machine & return change.


if (totalCredit>price){
  	arrKeys.forEach(x => this.coins[x] += credit[x])// put coins in vending machine
  	changeNeeded = totalCredit - price
    // PROBLEM BEGINS HERE
    for(let d=changeNeeded; d<0; d--){ 
    	while(this.coins[d]>0 && (changeNeeded - d)>=0){
      	changeObj[d] ? changeObj[d] ++ : changeObj[d] = 1
        this.coins[d]--
        changeNeeded -=d
      }
    }
   return changeObj //does not return as expected
  }
}


let vm = new VendingMachine({1:1, 2:0, 4:3, 6:2})

let result = vm.vending(12, {2:1, 6:3})
console.log(vm) //check if the credit is put into the machine (yes)
console.log(result)// returns empty object
&#13;
&#13;
&#13;

如何让程序返回更改对象?

1 个答案:

答案 0 :(得分:0)

我认为问题在于循环的条件本身。 实际上,你有:

--optimize-dedupe

但是你想循环减少d(变化)随着时间的推移。因此,您的情况应该以相反的方式改变(使用for (let d=changeNeeded; d<0; d--){ 而不是>):

<

我希望这就足够了。