how to write a coin counter function with only conditional statements in JavaScript? - Stack Overflow

I am still a beginner, a total noob here so please be patient, I came accross this exercise which is ba

I am still a beginner, a total noob here so please be patient, I came accross this exercise which is basically spreading the amount of pennys/cents into sufficient number of coins of 25,10,5,2,1.

I was trying to write only with if conditionals as I'm still learning, so not familiar with the built-in functions.

the function works well with the number 65 tested, giving an array of 25 ,25 ,10 ,5 respectively

however, when I tested with the number 46, it gave an array of 25, 25, 10, ,5 25, 10, 10, 1 which is obviously false and something is clearly wrong with my function.

Would you please point the mistake to me.

here is my code and thanks in advance.

var co = [];
function coin(n){ //46


// co = [25,]


    if (n>=25){
        co.push("25");
        n = n-25;
        coin(n);
    }

    else if (n>=10){
        co.push("10");
        n = n-10;
        coin(n);
    }


    else if (n>=5){
        co.push("5");
        n = n -5;
        coin(n);
    }

    else if (n>=2){
        co.push("2");
        n = n - 2;
        coin(n);
    }

    else if (n>=1){
        co.push("1");
        n = n - 1;
        coin(n);
    }




    else if (n == 0){console.log(co);}


}

I am still a beginner, a total noob here so please be patient, I came accross this exercise which is basically spreading the amount of pennys/cents into sufficient number of coins of 25,10,5,2,1.

I was trying to write only with if conditionals as I'm still learning, so not familiar with the built-in functions.

the function works well with the number 65 tested, giving an array of 25 ,25 ,10 ,5 respectively

however, when I tested with the number 46, it gave an array of 25, 25, 10, ,5 25, 10, 10, 1 which is obviously false and something is clearly wrong with my function.

Would you please point the mistake to me.

here is my code and thanks in advance.

var co = [];
function coin(n){ //46


// co = [25,]


    if (n>=25){
        co.push("25");
        n = n-25;
        coin(n);
    }

    else if (n>=10){
        co.push("10");
        n = n-10;
        coin(n);
    }


    else if (n>=5){
        co.push("5");
        n = n -5;
        coin(n);
    }

    else if (n>=2){
        co.push("2");
        n = n - 2;
        coin(n);
    }

    else if (n>=1){
        co.push("1");
        n = n - 1;
        coin(n);
    }




    else if (n == 0){console.log(co);}


}
Share Improve this question asked Mar 7, 2016 at 0:02 Mohamed HegazyMohamed Hegazy 2734 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

The problem is that you don't clear the array when you call the function in the second time. You'll need to clear it every time.

you can make a new function Countcoin(n)

function Countcoin(n){
    co = [];
    coin(n)
}

and now call this function instead of coin


Or you can build only one function but using loop, not recursion.

var co = [];
function coin(n){ 
    co=[];
    while(n!=0){
        if (n>=25){
            co.push("25");
            n = n-25;
        }
        else if (n>=10){
            co.push("10");
            n = n-10;
        }
        else if (n>=5){
            co.push("5");
            n = n -5;
        }
        else if (n>=2){
            co.push("2");
            n = n - 2;
        }
        else if (n>=1){
            co.push("1");
            n = n - 1;
        }
    }
    console.log(co);
}

Your code works just fine. But you have only global array co which preserves previous answer. So I think you should initialize an array inside of your function, then return it.

You could do each conditional by:

  1. Simple division (round down)

  2. Assign the quotient to a var or element (like an output tag)

  3. Use the modulo for the next conditional

Snippet

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
fieldset { width: 20ex; font: 400 16px/1.4 'consolas'; color: #00e; }
legend { font:inherit; font-size: 1.25rem; }
input, label, output { padding: 1px 3px; font:inherit;}
input { width: 7ex; }
output { width: 5ex; }
</style>
</head>

<body>
<header></header>
<form id="change" name="change">
<fieldset>
<legend>coinCounter</legend>
<label for="inp1">$</label><input id="inp1" name="inp1" placeholder="0.00"><br/>
<label for="q">Quarters: </label><output id="q" name="q" for="inp1">0</output><br/>
<label for="d">Dimes:&nbsp;&nbsp;&nbsp; </label><output id="d" name="d" for="inp1">0</output><br/>
<label for="n">Nickels:&nbsp; </label><output id="n" name="n" for="inp1">0</output><br/>
<label for="p">Pennies:&nbsp; </label><output id="p" name="p" for="inp1">0</output>
</fieldset>
</form>
<footer>Hit <kbd>&#9166; Return</kbd> before typing</footer>

<script>
var inp1 = document.getElementById('inp1');

inp1.addEventListener('input', function(e) {
	delay(coinCounter(this.value), 5000 );
}, false);

function coinCounter($) {
	var denomination = $.split('.');
	var dollars = Number(denomination[0] * 100);
	console.log('dollars: '+dollars);
	var cents = Number(denomination[1]);
	console.log('cents: '+cents);
  var total = Number(dollars + cents);
  console.log('total: '+total);
	var modQ, modD, modN;
	
	if(total >= 25){
		var quarter = Math.floor(total / 25);
		console.log('quarters: '+quarter);
		document.getElementById('q').innerHTML = quarter;
	}
	modQ = total % 25;
	
	if(modQ >= 10){
		var dime = Math.floor(modQ / 10);
		console.log('dimes: '+dime);
		document.getElementById('d').innerHTML = dime;
	}
	modD = modQ % 10;
	
	if(modD >= 5){
		var nickel = Math.floor(modD / 5);
		console.log('nickels: '+nickel);
		document.getElementById('n').innerHTML = nickel;
	}
	modN = modD %  5;
	
	if(modN){
		var penny = Math.floor(modN);
		console.log('pennies: '+penny);
		document.getElementById('p').innerHTML = penny;
	}
	else {
		modN = 0;
	}
  return false;
}

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
  clearTimeout (timer);
  timer = setTimeout(callback, ms);
 };
})();
</script>
</body>
</html>

Since you mentioned you were learning, I thought I'd submit an alternative method -- I provided a step by step breakdown.

Built in functions used:

Array.prototype.reduce - applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

function coins(cents) {
    return [25, 10, 5, 1].reduce(function(totalDenoms, denom) {

    // if we have any values for this denomination, add it to the final array
    for (var i = 0; i < Math.floor(cents/denom); i++) {
        totalDenoms.push(denom);
    }

    // set the remaining amount of cents to process
    cents = cents % denom;

    // return the accumulated totals
    return totalDenoms;

    }, []);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745307413a4621794.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信