Javascript random min max doesn't work - javascript

I am trying to make a simple program for a tabletop game that calculates damage. So I want to use random between two integers with a couple of percentage stuff to calculate damage.
The problem is random doesn't work for me. It doesn't matter what numbers I set as min or max, it always starts from 0 to the number before max.
<script>
function showDiv() {
var armor = document.getElementById('armortype').value;
var damage = document.getElementById('dmgtype').value;
var min = document.getElementById('mindmg').value;
var max = document.getElementById('maxdmg').value;
document.getElementById('result').style.display = "block";
for (var i=0;i<100;i++)
{
var dmg_done = Math.floor(Math.random()*max+min+1);
document.getElementById('test').innerHTML += " " + dmg_done;
}
}
</script>
So for min = 3, max = 6 I get the following 100 numbers:
3 1 2 2 0 2 2 1 2 2 3 3 4 0 1 1 2 2 5 2 3 5 3 3 3 4 0 0 5 2 3 0 4 0 2 1 0 5 4 1 0 5 5 4 2 1 2 4 5 1 5 1 0 4 3 5 2 1 4 3 1 1 5 1 4 2 1 0 3 3 3 4 3 4 5 4 2 0 2 4 5 0 3 1 2 5 0 1 5 1 2 2 1 4 0 0 0 1 4 2
So it doesn't matter that min is 3, it randomizes from 0 and there is not even a single 6 in the result.

Demo:
http://jsfiddle.net/zprr6/
You want to utilize it as such:
var dmg_done = Math.floor(Math.random() * (max - min + 1) + min);
The reason it starts at 0, is because the Math.random function produces a float from 0-1 (as many JS functions and features do).
So, by telling it to start at max - min + 1, ie 4, it avoids using the 0 as a starting value.

Try replacing Math.floor(Math.random()*max+min+1) with Math.floor(Math.random() * (max - min + 1) + min)

So why don't you try calculating random like this
function getRandom (min, max) {
return Math.random() * (max - min + 1) + min;
}
Edit: to add to the comment
var valOne = $("#input-1").val(),
valTwo = $("#input-2").val();
$("#button").click(function() {
$("#answer-input").val(getRandom(parseInt(valOne), parseInt(valTwo)));
);

Found the problem. both min and max were used as strings, not numbers. So I just parsed them as ints like this:
var min = parseInt(document.getElementById('mindmg').value);
var max = parseInt(document.getElementById('maxdmg').value);
and it works flawlessly now

Try
Math.floor((Math.random() * (max+1-min))+min);
max+1 - so that the maximum is include, and +min so that the min is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,3,5,6,3,6,3,5,5,5,6,3,6,4,3,4,5,5,3,6,6,6,6,4,5,6,5,3,4,4,3,4,6,3,6,
On an additional note, getting the value of a textbox always returns a string, so the following (min and max) are both strings
var min = document.getElementById('mindmg').value;
var max = document.getElementById('maxdmg').value;
I would check that they are actually numbers, and cast them, before using them in the Math, something like
var min = +(document.getElementById('mindmg').value);
var max = +(document.getElementById('maxdmg').value);
putting the + at the front will casue a number cast IF IT CAN, if it can't, it will be NaN (Not a Number), so before you use, check that they are not NaN. Nan can easily be checked, as nothing equala Nan not even Nan so something like
if(min === min && max === max)
{
//... all good to use con..
}
will check that they are actually numbers as Nan will never equal NaN but 3 will always equal 3

Related

Explanation of Code: Dealing with min and max - Javascript [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 6 years ago.
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
}
I need a refresher on what the return statement is doing. I understand it creates a range for instance, 5 - 15. But I don't get why I'm subtracting the max from the min and adding + 1 and then +myMin.
But I don't get why im subtracting the max from the min and adding + 1 and then +myMin.
First remember that Math.random() returns a value in the range of [0, 1).
Lets start from the end:
+ myMin is done to ensure that the result is larger or equal to myMin.
Lets assume Math.random() returns 0. Then Math.floor(...) returns 0. If we didn't + myMin, return result would be 0 instead of myMin.
+ 1 is done to get random values that include myMax. Remember that Math.random() never returns 1, only values close to 1. I.e. the Math.floor(Math.random() * myMax) can never be myMax unless we add 1.
myMax - myMin is done because we do + myMin above. We have to account for increasing the result by myMin.
Lets assume Math.random() returns 0.5 and our range is 100 - 120. Without - myMin, we would get
Math.floor(0.5 * 120) + 100 = 60 + 100 = 160
That's clearly larger than 120. If we include - myMin:
Math.floor(0.5 * (120 - 100)) + 100 = (0.5 * 20) + 100 = 110
we get 110 which is exactly in the middle of our range (which makes sense intuitively since we get 0.5 as a random value).
Math.random returns float number between 0 to 1. For example if you take 1 to 10 range. Then Math.random will return minimum 0 and maximum 1 then you multiply it with 10-1=9. And you get 0 to 9. But when you add the minimum it will be increased to 1 to 10.
Correction - it's not creating a range, it is generating a random Integer number between a given range of numbers ( minimum and maximum number).
E.g. (5, 15) = (min, max)
Will result in a number that is in between this range.
Code explanation :
Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
Let's assume both max and min are = 15
So the above will look like:
Math.floor(Math.random() * (15 - 15 + 1)) + 15;
Which is equal to = 15, since 0 <= Math.random() * (1) < 1 so the floor of this is 0.
If you don't add that 1, it will not be valid for this corner case.
You add minimum to make sure the value remains between min and max.

Understanding the modulus operator

I have some code that loops through a collection of list elements and a collection of colours. It makes sure each list element is designated to a colour.
I understand everything about this apart from the modulus operator. I get that it finds and uses the remaining number, but I cannot for the life of me understand what it is doing here?
var li = document.getElementsByTagName('li');
var colors = ["salmon", "teal", "orange", "grey", "blue"];
var colorsCount = colors.length;
for ( var i = 0; i < li.length; i++ ) {
li[i].style.backgroundColor = colors[ i % colorsCount ]; // why does this work?
}
Since there is (potentially) a larger number of items in the li array, this prevents i from being outside the bounds of the colors array, since i % colorsCount can never be over colorsCount.
For example, if we had 10 elements in li, and 5 colors, i % colorsCount would be:
i i % colorsCount Color
-------------------------------
0 0 salmon
1 1 teal
2 2 orange
3 3 grey
4 4 blue
5 0 salmon
6 1 teal
7 2 orange
8 3 grey
9 4 blue
More Information on Modulo Operations.
i % colorsCount will set the bound of the index to be between 0 and colorsCount-1, thus ensuring you never index past the end of the array.
Since mod is the remainder, the remainder can never be greater than the divisor (which in this case, is the length of the array).
Perhaps this snippet may help you understand:
var s = ''
for (var i = 0; i < 20; i ++) {
s += (i % 5) + ', '
}
console.log(s)
The result is:
0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
Note how the number resets to 0 every time it reaches 5. The % colors.length just makes sure the index never goes above the array's length.
A more descriptive way of understanding:
0 % 5: 0/5 = 0, remainder 0
1 % 5: 1/5 = 1/5, remainder 1
...
5 % 5: 5/5 = 1, remainder 0
6 % 5: 6/5 = 1 1/5, remainder 1
7 % 5: 7/5 = 1 2/5, remainder 2
...
It's cycling your colours. Because you only have a limited number of colours, and any number of possible list items, it makes sure that i will not overflow the bounds of your colors array.
The modulus operator returns the remainder of division. It allows you to loop through and reuse the colors array even though there are potentially less colors in the array than there are elements in your list to color.
If length is say 8,
5 % 1 == (5 / 1) = 0 remainder 1
5 % 2 == (5 / 2) = 0 remainder 2
5 % 3 == (5 / 3) = 0 remainder 3
5 % 4 == (5 / 4) = 0 remainder 4
5 % 5 == (5 / 5) = 1 remainder 0
5 % 6 == (5 / 6) = 1 remainder 1
5 % 8 == (5 / 7) = 1 remainder 2
5 % 7 == (5 / 8) = 1 remainder 3
As you can see, the remainders are what's returned by the mod operator, and they're always less than the length of the colors array.
why does i % colorsCount work?
What it does
This code cycles through colors. It does so using the modulus operator to ensure you're always within the bounds of the array.
How it does it
Modulus operation finds the remainder of division of one number by another.
In your case by taking i modulus the colorsCount:
0 % 5; // 0
1 % 5; // 1
1 % 5; // 2
3 % 5; // 3
4 % 5; // 4
5 % 5; // 0
8 % 5; // 3
The result of a modulus operation is the remainder after division of the left operand by the right operand.
So the line of code in question will always return some number between 0 and colorsCount-1.
You iterate from 0 until how many li elements you have. For this example, say 10.
You then look at the colors array and find the element for that iteration (i) and modulus by how many items are in the colors array.
In short, this is what's happening:
var colorsCount = 10;
1 % 10 = 1 // ... Access colors[1]; (teal)
2 % 10 = 2 // .... Access colors[2]; (orange)
3 % 10 = 3 // .... Access colors[3]; (grey)
4 % 10 = 4 // .... Access colors[4]; (blue)
5 % 10 = 5 // .... Access colors[5];
etc
If you are wondering why it will never access an element outside of the array, the answer is because as i becomes greater, the result becomes smaller.
For example, take iteration 8:
8 % 5 = 3
(Iteration 8, 5 elements in the array)
Therefore you are accessing colors[3];

I'm trying to use random function in Javascript?

var x = 1 + Math.Random() % 9;
if (x==1)
// do something
else if (x==2)
// do something else
I used this line — (1 + Math.Random() % 9) — in C++ to get a number between 1 and 9, but in JavaScript I'm getting a different result.
Math.random() returns a value between 0 and 1, so instead using the modulo operator you need to use a multiplication.
1 + (Math.random() * 9);
Finally, you should round or .floor() that value
var x = Math.floor( 1 + ( Math.random() * 9 ) );
or, shorter
var x = ~~( 1 + ( Math.random() * 9 ) );
There is no Math.Random() function in JavaScript. It's Math.random(). Note the capitalization.
To get a random number between a certain minimum and maximum value, do this:
var min = 1, max = 9;
Math.floor(Math.random() * (max - min + 1)) + min;
Further reading: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
In Javascript the Math.random function returns a number between 0 and 1. If you want to get a number between 1 and 9 you'll have to work with it a bit.
var number = ((Math.random() * 10) | 0) % 9 + 1
This will give you a result between 0 and 9
Math.floor(Math.random()*9)
And by the way, jQuery is a javascript framework. Math is a native javascript function

Need an explanation of this javascript

I have a question about this script I found and used. It works but I don't get why. The exercise was to make a list with random numbers from -50 to 50. The function below uses Math.floor(Math.random() * (the part i dont understand).
If I put this calculation on google I got as answer 151 and Math.random()*151 does not do from -50 to 50.
Can someone give me a clear explanation about this function below because I am sure that I am missing something.
this script works but I only want a clear explanation how
for (i = 0; i <= 100; i++)
{
Rnumber[i] = randomFromTo(-50,50);
}
function randomFromTo(from, to)
{
return Math.floor(Math.random() * (to - from + 1) + from);
}
to - from + 1 = 50 - (-50) + 1 = 101
Math.random() * 101 = number in range [0,101[
Math.floor([0,101[) = integer in range [0,100]
[0,100] + from = [0,100] + (-50) = integer in range [-50,50]
Which is exactly what is asked for.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
Math.random returns a floating-point, pseudo-random number in the
range [0, 1) that is, from 0 (inclusive) up to but not including 1
(exclusive), which you can then scale to your desired range.
which when multiplied with a number > 1 and floored gives you an integer
Math.random() - get only value between 0 and 1.
Math.floor( number ) get integer down rounded value from number.
You should:
function randomFromTo(from, to)
{
// you can use doubled bitwise NOT operator which also as Math.floor get integer value from number but is much faster.
// ~1 == -2 , ~-2 == 1 and ~1.5 == -2 :)
return ~~( --from + ( Math.random() * ( ++to - from )) )
}

How to generate random number with js from range starting from 1?

I've been using this code to generate a random number with js:
var max = 10;
Math.floor( Math.random() * ( max + 1 ) );
From what I understand that will generate a number from 0 to 10, but what if I want to generate a random number from 1 to 10? or from 5 to 10?
try this:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
If you want to start from x instead of 0, then:
Subtract x from max
Do everything else as normal
Add x to the result
You do from 0 to 9, then you add one to the result.

Categories