CoffeeScript function: Convert an amount to coins
CoffeeScript Function : Exercise-18 with Solution
Write a CoffeeScript function to convert an amount to coins.
Sample function : amountTocoins(46, [25, 10, 5, 2, 1])
Here 46 is the amount. and 25, 10, 5, 2, 1 are coins.
Output : 25, 10, 10, 1
HTML Code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="//jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
<title>Convert an amount to coins</title>
</head>
<body>
</body>
</html>
CoffeeScript Code:
amountTocoins = (amount, coins) ->
if amount == 0
[]
else
if amount >= coins[0]
left = amount - coins[0]
[ coins[0] ].concat amountTocoins(left, coins)
else
coins.shift()
amountTocoins amount, coins
console.log amountTocoins(46, [
25
10
5
2
1
])
Sample Output:
[25, 10, 10, 1]
Live Demo :
See the Pen coffeescript-exercise-18 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics