Why is My Random Number in Javascript Code Concatenating Rather Than Adding? - javascript

I'm writing a basic random number generator (self teachingvia freeCodeCamp, going to use it for games with my 2 little boys). I'm using a basic HTML with no CSS added as the DOM and Javascript client side for the function (client side as my eldest is 5 and we have a family blog he loves to show people).
The problem is that the code below is working to a point - the Math random function is fine, it works with Math.floor well and the multiplcation * (maximum - minimum +1) is all working as expected.
The issue is that the last segment is not working: + minimum. From the results I have looked at the formula is generating a result up to and including the multiplcation bracked, but then concatenating the minimum on the end, rather than adding it to the result.
I have converted the maximum and minimum values to integers via parseInt when I first discovered the problem, in case there was an issue there (I didn't see why as they both worked fine in the multiplcation bracket), but that of course made no difference.
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
parseInt(maximum);
parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
<div id="dice">
<form name="randomDice">
<h1>Get a random number</h1>
<p>Maximum</p>
<input id="maximum" type="number" name="random"><br>
<p>Minimum</p>
<input id="minimum" type="number" name="random"><br>
<br>
<button onclick="randomNumberFunction()">Get a random number</button>
</form>
</div>
I'm looking to be able to capture the minimum and maximum values a user inputs, and produce a random integer from that range. Instead I get values like 01 when I input min 1, max 4, or 21. or 63 when inputting min 3, max 10.

You aren't assign value when you cast minimum and maximum variables
Try this:
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
maximum = parseInt(maximum);
minimum = parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}

Related

How to add functions on randomly generated numbers

Is it possible to add a function on randomly generated numbers. For example I used getRndInteger(min, max), Math.floor() and Math.random() to generate random numbers, and within those numbers you want to add function to see which of those generated numbers is the biggest. I was thinking maybe it was possible to put each randomized number in array and use Math.max() on them, but I'm not quite sure how you put those numbers in a function that for example on click, you see the generated numbers and result(the biggest number of them all) underneath it. I mainly want to know if it's even possible and if so, how. I'd be super thankful!
So I specifically want to use a random number from -35 to 76 including -35 and 76. I made a button that on click shows the randomized number. Another problem to me is, I'm not sure how to add a randomized number one after another instead of adding new one on click. (Haha sorry if it's a super newbie problem). Then I put an id on paragraph that displays the answer. And I was thinking to use the document.getElementById("") for the Math.max.apply() and make another paragraph with another ID that displays the answer.
<button onclick="document.getElementById('result').innerHTML = getRndInteger(-35,76)">Click Me</button>
Chosen number:
<p id="result"></p>
Biggest number:
<p id="result2"> </p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
<script>
Array.max = function(document.getElementById("result");) {
return Math.max.apply(document.getElementById"result");
};
</script>
When I put .getElementById() in Math.max.apply() as an array, even on click, java script no longer loads randomized number. Maybe you have to add id to the answers or something, I'm all out of ideas here. Any help would be greatly appreciated! I'd also like if I'd still use Math.max() to do this and avoid any overly complicated codes to understand the issue and use the answer in the future codes. Thank you loads!
You should store the previously generated maximum number to be able to determine that the currently generated number is higher than it. See snippet to get an idea.
(() => {
let max = null;
const range = {
min: -35,
max: 76
};
const result = document.querySelector("#result");
const maxResult = document.querySelector("#resultMax");
const allNrs = document.querySelector("p#all");
document.querySelector("button").addEventListener("click", handleButtonClick);
function handleButtonClick() {
const someRandomNumber = getRndInteger(range.min, range.max);
result.textContent = someRandomNumber;
max = max && someRandomNumber > max
? someRandomNumber
: max
? max
: someRandomNumber;
maxResult.textContent = max;
allNrs.textContent += ` ${someRandomNumber} `;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
})();
#all {
max-width: 400px
}
<p>
<button>Click Me</button>
</p>
Random number:
<span id="result"></span>
<br>Biggest number until now:
<span id="resultMax"></span>
<div>
<br>All numbers until now:
<p id="all"></p>
</div>

Var won't exceed billion

EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!

Can I accurately calculate an average from a medium size set of 2 d.p. numbers using JavaScript?

I need to find the average of a set of values and after doing some reading am not sure if JavaScript is able to produce an accurate result or not.
Each value has a precision of 2 d.p. and there could be up to 10000 of them between -100000.00 and 100000.00. The result also needs to be to 2 d.p.
From what I can see it is usually the figures around the 16th decimal place that are inaccurate which means that I would have to average an extremely large set before affecting my result. Is the best way of doing it to simply sum all of the values, divide by the total number and then use a toFixed(2)?
You could take advantage of your 2dp prevision, and multiply all your numbers by 100 first, then do the mathematics using integers. EG, a float error occurs in this simple average (I am just using 1dp for this example):
(0.1 + 0.2) / 2
0.15000000000000002
But this works:
(0.1*10 + 0.2*10) / (2*10)
0.15
Some good reading here:
http://floating-point-gui.de/basic/
and here:
How to deal with floating point number precision in JavaScript?
and a really precise fix to do it using decimals is to use this:
https://github.com/dtrebbien/BigDecimal.js
Example for 2 dp:
var numbers = [0.10, 0.20, 0.30]
var simple_average = numbers.reduce(function(a, b) {
return a + b
}) / numbers.length
console.log(simple_average)
var smart_average = numbers.map(function(a) {
return a * 100
}).reduce(function(a, b) {
return a + b
}) / (numbers.length * 100)
console.log(smart_average)
This demo can be run here -- http://repl.it/e1B/1

toFixed Isn't Doing Anything

I'm teaching myself JavaScript and have run into a problem with toFixed(). I'm working through an amortization calculator; and, one of the steps returns a number with a huge number of decimal places. I'm trying to cut it down to 4 decimal places.
Be advised the sample code has a lot of explanatory HTML in it. It's only there so that I can work through the steps of the equation. Also, when I add one to the very long number, it adds the numeral one to end of the scientific notation.
var paymentamount;
var principal=250000;
var interestrate = 4.5;
var annualrate = interestrate/12;
var numberofpayments = 360;
document.write("This is the annuitized interest rate: "+ annualrate +"%");
document.write("<h3> Now we add 1 to the annualized interest rate</h3>");
var RplusOne = annualrate + 1;
document.write("<p> This is One Added to R: " + RplusOne + "%");
document.write("<h3>Next RplusOne is Raised to the power of N </h3>");
var RRaised = (Math.pow(RplusOne, numberofpayments)).toFixed(4);
document.write("<p>This gives us the following very long number, even thought it shouldn't: " + RRaised);
document.write("<h3>Now we add one to the very long number </h3>");
var RplusOne = RRaised + 1;
document.write("<p>Now we've added one: " + RplusOne);
From MDN's documentation:
If number is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
The problem is that you are using 4.5 as your interest rate instead of 0.045, so doing this:
Math.pow(4.5 / 12 + 1, 360)
gives you a huge number (6.151362770461608e+49 or 6.15 * 10^49 to be exact). Change your interest rate to 0.045 and you will get what you are expecting.
As for the var RplusOne = RRaised + 1 line, the problem here is that RRaised is a string because of toFixed. I would only call toFixed when you're displaying things, and not at any other time; the primary reason for this would be to avoid rounding errors in subsequent calculations, but has the added benefit that your variables remain numbers and not strings.

how to add and subtract on single click with two different values

I am creating a game,now as the code,when i click attack,the enemies power lowers randomly,but i want same with player but the random value should be different from the one in enemies ..if possible,can there aso be a heal option to randomly raise players power and decrease it too because enemy is still attacking
appearence(current): http://amerish.webs.com/amerish/testgame.html
code:
<head>
<script>
var playerHealth=100;
var enemyHealth=100;
var strength=10;
function begin(){
document.getElementById'playerhealth').innerHTML= playerHealth;
document.getElementById('enemyhealth').innerHTML =enemyHealth;
}
function hitEnemy(){
var attack=Math.floor(Math.random()*20 +strength);
enemyHealth =enemyHealth - attack;
document.getElementById('damage').innerHTML= attack;
document.getElementById('enemyhealth').innerHTML =enemyHealth;
}
</script>
<body onload="begin()">
<input type="button" name="doit" id="doit" value="Attack!"
onclick="hitEnemy();">
<br /
<span>playerhealth</span>
<div style="font-ize:3em;"id="playerhealth"></div>
<span>enemyhealth</span>
<div style="font-size:3em;"id="enemyhealth"></div>
<br />
<span>You Did:</span><span style="font-size:3em;"id="damage"></span>
<span>damage</span>
</body>
This question looks like homework, did you write the code so far yourself? If you didn't, try to read through it and understand what each function is doing and where it is being invoked from.
the random value should be different from the one in enemies
Q: How can I generate random integers?
A: Here is a general-use function to generate pseudo-random integers
function rand_int(max, min) {
min = min | 0;
if (max === (max | 0))
if (max < min)
throw new RangeError("Range cannot be negative [" + min + '..' + max + ']');
else
return min + Math.floor(Math.random() * (max - min + 1));
throw new TypeError("Expected Integer for max but recieved: " + max);
}
Explanation: The random number is coming from Javascript's own Math.random which is between 0 and (but not equal to) 1. The x | 0 used to convert variables to 32-bit integers. Math.floor is used to change the floating point number into an Integer by always "rounding down". It works better than x | 0 for distributions over positive-and-negative numbers
can there aso be a heal option to randomly raise players power
Q: How can I add a random number to player's health?
A: Make a second <input> type button which causes something like the following to happen
playerHealth += rand_int(10); // add between 0 and 10
and decrease it too because enemy is still attacking
Q: Where do I put the code for the enemy turn?
A: Make a copy of the function hitEnemy, rename it to hitPlayer and change all occurances of enemy to player inside it. Then invoke it after hitEnemy is called, for example
<input
type="button" name="doit" id="doit"
value="Attack!" onclick="hitEnemy();hitPlayer();"
/>

Categories

Resources