Generating random numbers in Javascript!
This week at HackerYou, we are learning javascript!! I am super excited for it. I have a somewhat reasonable background in programming from my undergrad (mostly in Fortran90 and Matlab), but it's a little rusty. Our first day was nice because it was mostly a review of conditional logic, booleans, and loops.
I decided to program a rock paper scissors game, which I've included in case anyone wants to walk through it. But I've noticed the most confusing part tends to be the 'random' method on the 'Math' object. So I've decided to focus on explaining that.
First, I set player1 and player2 to a random number (either 1, 2, or 3) using the code below:
Math.ceil(Math.random()*3)
Basically, Math.random will give you a random number between 0 and 1. But, we'd like to expand that range so that it goes from 0 to 3. In order to do that, we multiply the random number by 3. Next, since we want to deal with whole numbers, we use Math.ceil on our random number between 0 and 3. Math.ceil works to round every number up to the next whole number - this will give use random numbers that are either 1, 2, or 3. If ever you wanted random whole numbers from 13 to 40 (including 40 but not 13), for example, you would say:
Math.ceil(Math.random()*(40 - 13) + 13)
The best way to test your code is to see what number would be generated if Math.random() is 0, and then test what would happen if it's 1. In the above case, if Math.random() is equal to 0:
Math.ceil(0*(40-13) + 13) = Math.ceil(0 + 13) = Math.ceil(13) = 13
This would represent the very lowest possible generated number. However, 0 will not likely be generated by Math.random(), so the lowest number will effectively be 14. Now, let's try Math.random() = 1.
Math.ceil(1*(40-13) + 13) = Math.ceil(40 - 13 + 13) = Math.ceil(40) = 40
This represents the highest possible number! You know can be sure that every number will be a whole number between 13 and 40 :) Check out the rock paper scissors game to see how I integrated this method into my game (rock = 1, paper = 2, scissors = 3) with a random number generator!