Vending Muchine

node v8.11.3
version: 1.0.0
endpointsharetweet
// 동전 단위와 개수 const coins = { 1000: 4, 500: 3, 100: 5, 10: 10 }; //result 배열. [ 성공 여부 , 1000원 동전, 500원, 100원, 10원 ] const result = calculateChanges(5230, 2500, coins); if (!coins.succeed) { let str = ""; for (measure in result) { if (measure === 'succeed') { continue; } str += measure + "원: " + result[measure] + "개 / "; } console.log(str); } else { console.log("동전 부족으로 돈을 반환할 수 없습니다.") } function calculateChanges(inputMoney, cost, baseCoins/*['(단위)':(개수)]*/) { let change = inputMoney - cost; let returnVal = {}; // 동전 단위 받아와서 큰 순서로 소팅. const coinMeasures = []; for (measure in baseCoins) { coinMeasures.push(parseInt(measure, 10)); } coinMeasures.sort((a, b) => b - a); // 돈이 모자랄 때. if (cost > inputMoney) { console.log("돈을 더 넣어주세요."); change = inputMoney; returnVal.succeed = -1; } for(let count = 0; count<coinMeasures.length; count += 1){ const measure = coinMeasures[count]; if (baseCoins[measure] >= Math.floor(change / measure)) { returnVal[measure] = Math.floor(change / measure); change -= Math.floor(change / measure) * measure; if (coinMeasures.length - 1 === count && returnVal.succeed != -1) { returnVal.succeed = 1; } } else { returnVal[measure] = baseCoins[measure]; change -= baseCoins[measure] * measure; if (coinMeasures.length - 1 === count && returnVal.succeed != -1) { returnVal.succeed = 0; } } } return returnVal; } module.exports = { getChange: (inputMoney, cost, baseCoins) => calculateChanges(inputMoney, cost, baseCoins) }
Loading…

no comments

    sign in to comment