Class Notes


Randomness

  1. Javascript random

Javascript Random numbers


Random Numbers are used in programming for multiple reasons. Choosing random images (banners, ads), messages or numbers for games, such as, lotteries. There are an infinite number of ways to use random numbers in art.

To create a random integer with Javascript, we must use two Javascript methods - Math.random() and Math.floor().

Math.random() generates a random number between zero and just less than 1 (ie. 0.99999...). Each time the code is run, it will create a new random number.

Math.floor() rounds DOWN to the nearest integer or round number. For example Math.floor(1.85) would equal 1.

Example 1

This will alert a random number when the link is clicked:

<script type="text/javascript">
      function alertRandomNumber() {
            alert(Math.floor(Math.random() * 100 + 1));
      }
</script>

<a href="javascript: alertRandomNumber();">Generate a random number between 1 and 100.</a>

Generate a random number between 1 and 100. (in the code we add 1 to it so it does not start at 0.)

Example 2

This example uses Math.random to retrieve a random URL from an array
<script type="text/javascript" >
      var myURLs = new Array("http://www.bgsu.edu", "http://www.syr.edu", "http://www.cia.edu", "http://www.cmu.edu");

      function alertRandomLink() {
            var myRandom = Math.floor(Math.random() * myURLs.length);
            var randURL = myURLs[myRandom];
            alert(randURL);
      }
</script>
Alert random link

Example 3

Instead of just alerting the url, lets try directing the user to a random URL:

<script type="text/javascript" >
      function randomPage() {
            var myURLs = new Array("http://www.bgsu.edu", "http://www.syr.edu", "http://www.cia.edu", "http://www.cmu.edu");

            var myRandom = Math.floor(Math.random() * myURLs.length);
            window.location = myURLs[myRandom];
      }
</script>

//if you wanted to open a new window rather than having the URL load into the current one, you would use window.open

Go to a random page

Example 4

Random Images - Displays a different image everytime the window is refreshed.
NOTE: Make sure images exist in a folder in your website first!
<script type="text/javascript" >
      var myPix = new Array( "../images/fruit1.jpg" , "../images/fruit2.jpg" , "../images/fruit3.jpg");

      function choosePic() {
            var randomNum = Math.floor( Math.random() * myPix.length);
            document.getElementById('myPicture').src = myPix[randomNum];
      }

</script>


<body onload="choosePic();"> //call function using the ONLOAD in the body tag
      <img src="../images/fruit1.jpg" id="myPicture">
</body>


NOTE: Do NOT put width and height in the image tag unless the images are all the same size and proportion.

USE this function and send it the start and end number for the random range you want:

function chooseNum(theMin, theMax) {
   var theRange = (theMax - theMin) + 1;
   var randomNum = Math.floor((Math.random() * theRange) + theMin); 
   return randomNum;
}

Here is an example using getElementById and randomness:
Random size, position and color
 <style type="text/css">
     #theSquare {
         position:absolute;
         top: 25px;
         left: 25px;
         width:50px;
         height:50px;
         background-color:#4A2F22;
         cursor: pointer;
      }
      #theRectangle {
         position: absolute;
         top: 50px;
         left: 100px;
         width: 100px;
         height: 25px;
         background-color:#AA3300;
         cursor: pointer;
      }
      #theLine1 {
         position: absolute;
         top: 100px;
         left: 0px;
         width: 200px;
         height: 4px;
         background-color:#000000;
         cursor: pointer;
      }
      #theLine2 {
         position: absolute;
         top: 112px;
         left: 0px;
         width: 200px;
         height: 6px;
         background-color:#000000;
         cursor: pointer;
      }
      #theLine3 {
         position: absolute;
         top: 126px;
         left: 0px;
         width: 200px;
         height: 8px;
         background-color:#000000;
         cursor: pointer;
      }
  </style>
  <script type="text/javascript" >
      function chooseNum(theMin, theMax) {
         var theRange = (theMax - theMin) + 1;
         var randomNum = Math.floor((Math.random() * theRange) + theMin); 
         return randomNum;
      }

      function changeSize(elem, theMin, theMax) {
         var size=chooseNum(theMin, theMax);
         document.getElementById(elem).style.width = size + "px";
         document.getElementById(elem).style.height = size + "px";
      }

      function changePosition(elem, theMinX, theMaxX, theMinY, theMaxY) {
         document.getElementById(elem).style.top = chooseNum(theMinY, theMaxY) + "px";
         document.getElementById(elem).style.left = chooseNum(theMinX, theMaxX) + "px";
      }

      function changeColor(){
         colors = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", 
"c", "d", "e", "f"); digits = new Array(); theColor=""; for (i=0;i<6;i++){ colorPart = Math.floor(Math.random() * 16); digits[i]=colors[colorPart]; //alert(colors[colorPart]); theColor = theColor+digits[i]; } theColor = "#"+theColor; document.getElementById("theLine1").style.backgroundColor = theColor; document.getElementById("theLine2").style.backgroundColor = theColor; document.getElementById("theLine3").style.backgroundColor = theColor; } </script> </head> <body> <div id="theSquare" onclick="changeSize('theSquare', 25, 200);"></div> <div id="theRectangle" onclick="changePosition('theRectangle', 50, 500, 200, 400);"></div> <div id="theLine1" onclick="changeColor();"></div> <div id="theLine2" onclick="changeColor();"></div> <div id="theLine3" onclick="changeColor();"></div> </body>