Greedy Algorithm - javascript

I am writing a piece of code, when a user enters the amount of change owed, returns the minimum amount of coins to equal that change. For instance, assuming only quarters, dimes, nickels and pennies are used. You enter $1.00. The number my code will render on the screen is 4 (4 quarters equaling a dollar). However, I am experiencing a small bug. If you type in $0.41 for example, you'd expect the code to render 4 again (1 quarter + 1 dime + 1 nickel + 1 penny is the minimum amount of permutations to equal 41 cents), but it doesn't, it renders 5.44. Please help! Thank you in advance.
document.write("Hi,how much change is due? ");
function greed () {
var n = document.getElementById('change').value;
if (n >=0)
{
function amount (amt){
return amt/25 + (amt%25)/10 + ((amt%25)%10)/5 + ((amt%25)%10)%5;
}
document.write(amount(Math.round(n*100)));
}
else {alert("Invalid Amount!")};
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Greedy! </title>
<script type="text/javascript" src="greedy.js" ></script>
</head>
<body>
<form>
<fieldset>
<input type="number" id="change" name="change" value="0"/>
<input type="submit" id="submit" name="submit" value="submit" onclick="greed();"/>
</fieldset>
</form>
</body>
</html>

The main problem here is that you're not treating the numbers as integers, so you get decimal numbers everywhere. Let's use your example (0.41):
amt = n*100 = 41, so let's go to the return:
return amt/25 + (amt%25)/10 + ((amt%25)%10)/5 + ((amt%25)%10)%5
which is the same as
return 41/25 + (41%25)/10 + ((41%25)%10)/5 + ((41%25)%10)%5
as you know, 41/25 =/= 1, same with (41%25)/10 = 16/10 =/= 1 and ((41%25)%10)/5 = (16%10)/5 = 6/5 =/= 1, but you don't care about that in the code so you end up adding those decimal numbers till the end, and get weird values.
You must use parseInt() to get Integer values, so it should look like this:
return parseInt(amt/25) + parseInt((amt%25)/10) + parseInt(((amt%25)%10)/5) + ((amt%25)%10)%5
To show it works:
document.write("Hi,how much change is due? ");
function greed () {
var n = document.getElementById('change').value;
if (n >=0)
{
function amount (amt){
return parseInt(amt/25) + parseInt((amt%25)/10) + parseInt(((amt%25)%10)/5) + ((amt%25)%10)%5;
}
document.write(amount(Math.round(n*100)));
}
else {alert("Invalid Amount!")};
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Greedy! </title>
<script type="text/javascript" src="greedy.js" ></script>
</head>
<body>
<form>
<fieldset>
<input type="number" id="change" name="change" value="0"/>
<input type="submit" id="submit" name="submit" value="submit" onclick="greed();"/>
</fieldset>
</form>
</body>
</html>

Related

total numbers printing and calculating with two functions

I'm total beginner with programming and javascript, i have coded small thing where is two inputs, user writes number on each and program plus it and gives total numbers below it
function printTotal(a,b){
// this function should take values as a parameter
}
function calculateTotal(a,b){
var c=a+b;
// this function should calculate and return
}
document.getElementById("results").innerHTML = "Total= " +printTotal(a,b) ;
<div class="keski">
<form id="f">
<input type=text id="n1"><br>
<input type=text id="n2"><br>
</form>
<button class="g" type="button" onclick="printTotal(f.n1.value, f.n2.value)">Count</button>
<div id="results"></div>
</div>
i have two functions which should help each other in order to make this possible( i have commented the code) , i know how to make this with one function, but dont know how to make it with two functions, do i need to put functions inside each other(nested)? sory english is not my mother language.
In calculateTotal function you need return value. In printTotal you can get value in 2 input and call calculateTotal for calculate total and print it.
Try this code:
function printTotal(a, b){
// this function should take values as a parameter
// print total
document.getElementById("results").innerHTML = "Total= " + calculateTotal(a, b)
}
function calculateTotal(a,b){
// need return total
return Number(a) + Number(b);
// this function should calculate and return
}
<div class="keski">
<form id="f">
<input type=text id="n1"><br>
<input type=text id="n2"><br>
</form>
<button class="g" type="button" onclick="printTotal(f.n1.value, f.n2.value)">Count</button>
<div id="results"></div>
</div>
function printTotal(a,b) {
return calculateTotal(a,b);
}
function calculateTotal(a,b) {
return a+b;
}
Is this what you mean?
You can try with this changes. Basically I moved the code that assigns value to results div, and changed a method call there.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
</style>
</head>
<body>
<div class="keski">
<form id="f">
<input type=text id="n1"><br>
<input type=text id="n2"><br>
</form>
<button class="g" type="button" onclick="printTotal(f.n1.value, f.n2.value)">Count</button>
<div id="results"></div>
</div>
<script>
function printTotal(a,b){
document.getElementById("results").innerHTML = "Total= " +calculateTotal(a,b) ;
}
function calculateTotal(a,b){
var c = Number(a) + Number(b); //I use the 'Number' method here in order to avoid a and b being concatenated (treated like strings)
return c; //This return was missing so we can return value to calling method.
}
</script>
</body>
</html>

how do i make a button generate a random number and each time the button is clicked a new number is generated and added to the previous number

I need help making a button generate a random number in java script, i would like when the button is pressed for it to generate a random number between 1-10 and and then once the button is pressed again for it to generate a new random number but the sum of both number to show each time the button is presses. For example button is presses and the computer generates 3 button is presses and computer generates 2 but shows the sum of 2+3 so 5
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Merienda+One' rel='stylesheet' type='text/css'>
<title>
Blackjack
</title>
<body>
<head>
<h1>
<i>BLACKJACK</i>
</h1>
<h4>
Computers Cards:
<input type="text" id="computerscards">
<br>Player 1 cards:
<input type="text" id="playerscards">
</h4>
</head>
<input type="button" value="start" onclick="document.getElementById('playerscards').value =
random();document.getElementById('computerscards').value = 18">
<input type="button" value="deal" onclick="document.getElementById('playerscards).value = dealcard">
<input type="button" value="stand" onclick="">
<input type="button" value="next" onclick="">
<p>Press hit if you would like to draw another card
<br> press stand if you do not wish to draw another card
<br> press next if you want to start the next round</p>
</body>
<script src="java.js"></script>
</html>
JAVASCRIPT
var total =
var randomnumber = Math.floor(Math.random() * 10 + 1);
function random() {
return randomnumber;
}
function dealcard() { }
When you set var total = multiple times, you are overwriting that variable. Instead, you should be setting it as a static value of 0 to start with, and updating it inside of the function that you call on button click. You can add to the existing value with total +=, which is a shorthand way of saying total = total + ....
Here's a really stripped-down example showcasing this:
var total = 0;
function dealcard() {
total += Math.floor(Math.random() * 10 + 1);
document.getElementById('playerscards').value = total;
}
Player 1 cards: <input type="text" id="playerscards">
<br />
<button onclick="dealcard()">Deal</button>
Hope this helps! :)

How can i save a value in the textbox to a variable

I want to store the value given in the text box in a variable. I am beginner to javascript. Please help me out. Here s my code.
<!DOCTYPE html>
<html>
<body>
Days of Journey: <input type="text" id="doj" name="daysofjourney">
<input type="button" value="submit" onclick="dayscounter()">
<script language="javascript" type="text/javascript">
var travel = document.getElementById("doj").value;
function dayscounter() {
var days;
for(days = 1; days <= travel; days++) {
document.write(days);
}
}
</script>
</body>
</html>
You nearly had it already...
function dayscounter() {
var travel = document.getElementById("doj").value;
var days;
for(days=1;days<=travel;days++)
{
document.write(days);
}
}
The problem was, that your first assignment of the variable travel is made as soon as the HTML code is loaded. The user can't have made an input yet at that time, thus the variable stays empty. If you include document.getElementById("doj").value inside the function, you will get the value at that specific time you launch the function.
Just parse value to int
var travel = +(document.getElementById("doj").value;);
You can use 'value' attribute of an text input to set it's value like:
<input type="text" id="textid" value="value content" />
and you can do your function like this:
<script language="javascript" type="text/javascript">
function dayscounter()
{
var travel = document.getElementById("doj").value;
var days;
var result = "";
for (days = 1; days <= parseInt(travel); ++days)
{
document.getElementById("result").value += " " + days;
}
}
</script>
Days of Journey:
<input type="text" id="doj" name="daysofjourney" />
<input type="button" value="submit" onclick="dayscounter()" />
<p>
<input type="text" id="result" />
</p>

Navigation list improvement needed

I made a simple html navigation list + some javascript. The thing is that i want a value to be returned when i select an option and click submit , but the value just vanishes in like 1 sec , here is the code:
<!doctype html>
<html>
<head>
<title>lol</title>
<meta charset="utf-8">
</head>
<body>
<form action="" name="form">
<input type="text" id="hp">
<select name="" id="lol">
<option value="neki1">neki1</option>
<option value="neki2">neki2</option>
<option value="neki3">neki3</option>
</select>
<input type="submit" onmousedown="radi()">
</form>
<script type="text/javascript">
function radi () {
var x = document.getElementById('lol').selectedIndex,
y = document.getElementById('lol').options,
z = Number(document.form.hp.value),
zSum = 0;
if(y[x].text === "neki1"){
zSum = z + 20;
}
else if(y[x].text === "neki2" ){
zSum = z + 35;
}
else if(y[x].text === "neki3" ){
zSum = z + 55;
}
document.form.hp.value = zSum;
}
</script>
</body>
</html>
EDIT:Also i want the old value to subtract if i change the option :)) , and yes the first question has been answered.
for 2nd Question
user parseInt() method of javascript to convert value from textbox back to integer.
and if the value is non 0 then do the substraction as needed.
parseInt(document.form.hp.value)
That's because you're not stopping the form from submitting and the page is reloading. Change the button code to:
<input type="submit" onclick="return radi()">
and at the end of your function add
return false;
jsFiddle example

JavaScript and HTML assignment

Okay, I'm ashamed to be asking, but it just isn't clicking. My brother-in-law has an assignment to have a text box and then a command button. When the button is pressed, it will loop 10 times printing whatever was in the text box. Should be simple - I know!
I know the error is on this line:
<input type="button" value="Press Here" onClick="sayit(document.getElementById('myTextField').value) ">
Here's what we have:
<html>
<head>
<title> Homework #11 part 2 </title>
<script type="text/javascript">
function sayIt(var message){
count = 1;
num = 10;
while (count <= num) {
document.write(message);
document.write("<br/>");
count = count + 1;
}
}
</script>
</head>
<body>
<p>
Type in a phrase.
<input type='text' id='myText' />
<br />
<input type="button" value="Press Here" onClick="sayit(document.getElementById('myTextField').value) ">
</p>
</body>
The code has three thins wrong.
1) function sayIt(var message) should be function sayIt(message)
2)onClick="sayit(....)" should be onClick="sayIt(....)"
sayIt is function name
3)document.getElementById('myTextField').value should be document.getElementById('myText')
myText is input element's id attribute
You've got three things wrong.
http://jsfiddle.net/userdude/jcfD8/
Hints - you don't need var in your function declaration, your id is not right, and you "misspelled" sayIt
( ^ If you care to see the answers, they are above ^ )
Invest in Firebug. It gave me all the answers I needed. ;)

Categories