Reputation: 1449
I'm new to JS function and objects I'm trying to iterate an array...this is my sample code which i was trying to get the multiples of coins with an input value
var flag=0;var chipval=0;var num=0;
var main = function(coins){
var coinsarr = [1,5,10,25,50,100,500,501];var length=coinsarr.length
var remval = coins;
var coinskey = "";
while(flag==0){
for(i=0;i<length;i++){
if(coinsarr[i]>remval){
chipval = coinsarr[i-1];
num = parseInt(remval/chipval);
if(remval%chipval==0){
flag = 1;
break;
}else{
remval=remval%chipval;
$flag = 0;
break;
}
}
}
coinskey = coinskey+","+chipval+":"+num;
}
coinskey = coinskey.replace(/(^,)|(,$)/g, "")
alert(coinskey);
}
when i run main(120), this will return 100:2,10:2(which is nothing by 100coins of 2 and 10coins of 2)
When i run main(720), i'm getting memory leaks...which says "Script on this page used too much memory"; Can anyone tell me, where the issue is or else is this the right way to proceed ??
Thanks for your time and patience...
Upvotes: 0
Views: 73
Reputation: 72857
A slightly cleaner option to get a amount of coins to make up a value, would be to build a object containing the values. Something like this will do the trick:
function coins(value){
var coinsarr = [1,5,10,25,50,100,500,501];
var out = {};
while(value > 0){
var i = 0;
while(coinsarr[i+1] <= value){
i++; // Find the coin to add.
}
var coin = coinsarr[i];
value -= coin;
if(!out[coin]){
out[coin] = 0;
}
out[coin]++;
}
return out;
}
coins(499);
// { Returns:
// 1: 4
// 10: 2
// 25: 1
// 50: 1
// 100: 4
// }
coins(21359);
// { Returns:
// 1: 2
// 5: 1
// 10: 1
// 100: 3
// 501: 42
// }
The advantage of this is that you can retrieve the values easier than having to parse a string:
var coinsObj = coins(499);
for(var key in coinsObj){
console.log(coinsObj[key] + ' times coin "' + key + '"' );
}
// 4 times coin "1"
// 2 times coin "10"
// 1 times coin "25"
// 1 times coin "50"
// 4 times coin "100"
Or just build a string like this:
var coinsObj = coins(499);
var outString = ''
for(var key in coinsObj){
outString += ',' + key + ':' + coinsObj[key];
}
outString = outString.substr(1); // Remove the leading comma.
Upvotes: 1
Reputation: 150030
If the value you pass into the function is greater than the highest value in the array you have an endless loop because the flag
never gets changed.
Specifically, the condition in this if
statement:
if(coinsarr[i]>remval){
...will never be true for 720
(or any other number more than 501
).
Also, should $flag = 0
not be flag = 0
? As it stands you create a global variable $flag
that never gets used.
Upvotes: 1