Reputation:
I have the following code to generate two random numbers
var attackRoll = Math.floor((Math.random()*6)+1);
var defenceRoll = Math.floor((Math.random()*6)+1);
When I run this code, it will generate two random numbers as expected. The only thing I notice, I wish to just ask to make sure I am not going crazy is... The first variable will always have the higher "Roll" or "Equal I have run this code an output the values so many, many times and not once has the second value been higher than that of the first.
Is this just me being silly? Or have I assigned the random numbers incorrectly?
Upvotes: 0
Views: 249
Reputation: 665574
I'm not sure what you want. To get one dice roll and another that is higher or equal use this:
var sides = 6;
var firstRoll = Math.floor((Math.random()*sides)+1);
var secondRoll = Math.floor((Math.random()*(sides+1-firstRoll)+firstRoll); // a lucky one :)
If you want to rolls and have the higher in the first variable, use
var sides = 6;
var firstRoll = Math.floor((Math.random()*sides)+1);
var secondRoll = Math.floor((Math.random()*sides)+1);
if (firstRoll >= secondRoll) {
higherRoll = firstRoll; // attackRoll
lesserRoll = secondRoll; // defenceRoll
} else {
higherRoll = secondRoll; // attackRoll
lesserRoll = firstRoll; // defenceRoll
}
Upvotes: 0
Reputation: 341003
Do you mean that attackRoll
is always greater than or equal than defenceRoll
? Absolutely not. In fact the probability of one being higher than the other is 50% equal.
Can you support your claims with a fiddle? Have you tried in different browser?
Upvotes: 1
Reputation: 14259
This appears to be a single user error - take a look at this jsFiddle, and you should find that the second number will be diverse:
the same,
higher,
or lower
than the first number.
Upvotes: 0