Randomization plays an important role in many applications like video games, physics modeling, cryptography, and even art and music! To start, JavaScript has a function Math.random()
that generates a decimal number between 0 and 1 (inclusive of 0, but not 1). If you would like to generate an integer in a different range, you can apply the following calculation:
var randomInteger = Math.floor(Math.random() * (maxInt - minInt + 1) + minInt);
where maxInt
and minInt
are the inclusive limits of your range, and Math.floor
rounds the calculation down to the nearest integer. See the example below for this in action.
maxInt
and minInt
to see what happens. Can they be negative integers?Math.floor
from the calculation. What happens when you don’t round the calculation?While you are welcome to use Math.random() and the corresponding calculations to adjust your range, the CodeHS library has a handful of randomization functions that you can use to make your programming simpler:
Random Integer (inclusive):
Randomizer.nextInt(min, max)
(generates a random integer between min and max integers)
Random Float (inclusive):Randomizer.nextFloat(min, max)
(generates a random float (ie decimal number) between min and max numbers)
Random Boolean:Randomizer.nextBoolean()
(generates a randomtrue
orfalse
boolean value)
Random Color:Randomizer.nextColor()
(generates a random hexadecimal color code in the format #RRGGBB)
Take a look at all four of these randomizations in the example below.
Below are a couple of examples to see different uses of the CodeHS Randomizer functions.
This first example is a snippet from an adventure video game. The randomizer is called when the player opens a treasure chest, generating a random number (and associated item) for the player to find.
The next example randomizes the color of the face’s eyes every time the user clicks on the canvas. You can find the color randomizer in the function colorChange()
.
colorChange()
, can you also have the color of the face and/or mouth change colors every time the user clicks?As you can see, there are a wide variety of uses for randomization in programming. Using the space below, try implementing one of the following tasks, or come up with something of your own!
true
or false
when the user runs a program and enters a fact (hint: use readLine("Enter fact: ");
to get the user input).