Go to:  Site entry | Site contents | Site index | Internet | JavaScript | Text bottom

Random  Index  Generation  JavaScript  (History–Controlled)

RANDOM JavaScript (stand-alone) is a function that generates a random index used for selection of an item from a predefined array representing item list.  Specific feature of RANDOM JavaScript is it's ability to "remember" a history of previous selections (for a predefined depth) and to make a best effort to ensure that newly generated random index is not present in index history.  The "memory" that holds the history of selections is an URL parameter list, which gets passed from one loading of HTML text to the next and from HTML to the JavaScript.

RANDOM JavaScript is a stand-alone one, which means that it s kept in a separate RANDOM.JS file that gets included into HTML <HEAD> (normally at its end) using the following operators (directory levelling may vary):


       <SCRIPT LANGUAGE=JavaScript SRC=../../RANDOM.JS></SCRIPT>
     

Included function is used in the <BODY> of HTML to select a random item from an item array defined within HTML <BODY>.

Note:

Before reading further you might want to look at explanation of the expression used to generate an integer random number within the specified range.



<!-- Random Index Generation (History Controlled)  04/21/1998–05/09/2006 -->
<!-- -------------------------------------------------------- 10/14/2003 -->
<!-- www.davar.net/RANDOM.JS                                             -->
<!-- Copyright (C) 1998–2003 by Vladimir Veytsel                         -->
<!--

// Generates and returns a random integer number in the range of [1-Max_Ind]
// that serves as an index for random selection of an array item.

// In order to provide a facility for selection of the specified index (handy
// for individual adjustment of items to be selected) RANDOM has the ability
// to be referenced with a SINGLE numeric argument, which indicates that it
// is the index to be returned as RANDOM value.

// The history of previous selections (comma-delimited index list) is passed
// as an argument and serves for generation a random index which is not present
// in the index history.

// A predefined history depth is maintained by placing a new index in front of
// the list and truncating list from the right to the specified length.

// The returned value is the modified history list, containing newly generated
// random index as its FIRST item.

// NOTE: Ideally a cycle of purely random attempts should work until a new
// index is generated (which is not present in the history of the previously
// generated indexes).  However, with this approach the response time tends
// to be more than what is acceptable.  To keep the response time always
// within the reasonable limits following method was chosen as a result of
// multiple experiments:

// - Total maximum number of attempts to generate a random index is limited
//   by total number of items in the item list (passed to RANDOM as Max_Ind).
// - Up to 3/4 of it can be used for attempts to generate index at random.
// - Remaining 1/4 of it can be used to generate index by "+1" incrementing.
// - If none of the above worked, returned value is index next to previous.

   function RANDOM(Ind_Hist,Hist_Depth,Max_Ind)
            {// Ind_Hist    - History of generated indexes (i1,i2,...,iN)
             // Hist_Depth  - History depth (limited by Max_Ind+1)
             // Max_Ind     - Maximum value of index range (minimum: 1)

             if ((Ind_Hist!="")&&              // Not empty AND
                 (Ind_Hist.indexOf(",")==-1))  // Is not the history list
                {if ((Ind_Hist<1)||
                     (Ind_Hist>Max_Ind))
                    document.write("<BR>Specified index <FONT COLOR=Red><BLINK><B>",
                                   Ind_Hist,"</B></BLINK></FONT> is out of item array range [<B>1</B>,<B>"
                                   ,Max_Ind,"</B>]<BR><BR>",
                                   "Please select index within the valid range of [<B>1</B>,<B>"
                                   ,Max_Ind,"</B>]<BR>",
                                   "or drop <B>?<FONT COLOR=Red>",Ind_Hist,"</FONT></B> altogether to select ",
                                   "item at random.<BR>")
                 else
                    return Ind_Hist+","   // Index for specific item selection
                }
             else
                {if (Hist_Depth>Max_Ind)  // Limit history depth by maximum index
                     Hist_Depth=Max_Ind

                 H=Ind_Hist.split(",",Hist_Depth)  // Split history list into index array

                 // document.write("Input_History=",H,"     ")  // Debugging

                 // Generate next index (non-repeatable for prev of specif depth)
                 // (logic below is necessary to minimize the response time)

                 Cnt=Max_Ind            // Attempts reverse counter
                 K=Math.round(Cnt/4*3)  // Number of purely random attempts
                 L=Cnt-K                // Number of "+1" incremental attempts
                 Valid=false            // Index valid (non-repeatable) flag

                 while (!Valid)      // Repeat until valid index is generated
                       {if (Cnt>=K)  // Attempts counter is within "random" range
                           i=Math.floor(Math.random()*Max_Ind)%Max_Ind+1
                        if (Cnt<L)   // Attempts counter is within "incremental" range
                           i=((i+1)%Max_Ind)+1      // Get "+1" incremental after previous
                        Found=false
                        for (j=0;j<Hist_Depth;j++)  // Compare new index with all previously saved
                            if (Number(H[j])==i)
                               Found=true           // Index is found among previously saved
                        Valid=!Found   // New valid is not found among previously saved
                        Cnt=Cnt-1      // Decrement the attempts reverse counter
                        if (Cnt<=0)    // Limit number of attempts to number of array items
                           {i=Max_Ind/2
                            if (H[0]!="")
                               i=((Number(H[0])+1)%Max_Ind)+1  // Get next seq index to prev displayed
                            Valid=true
                           }
                       }

                 for (j=Hist_Depth-1;j>0;j--)  // Push history array down to make room
                     H[j]=H[j-1]               // for the newly generated index

                 H[0]=i                        // Put new index at the top of history array

                 // document.write("     Output_History=",H,"<BR>")  // Debugging

                 return H.join()  // Join index history array into a comma-delimited list
                                  // and return it as a function value
                }
            }
//-->
  

Let's see how RANDOM JavaScript is used to generate indexes for Random Tagline selection.  This was the primary intention of RANDOM JavaScript development, though its usage is not limited to this example.

The list of taglines for random selection is defined as a JavaScript array placed in a separate file, reference to which is imbedded into the <BODY> of the calling HTML.  Since it was necessary to do individual adjustment for each tagline (the way it gets split into separate lines), the provisions were made to the RANDOM JavaScript permitting to suppress random selection and to select specified (by its number in the array) tagline instead.



<!-- Taglines for Random Selection  04/21/1998–03/30/2006 -->
<!-- ----------------------------------------- 05/24/1999 -->
<!-- www.davar.net/MISCL/TAGLINES/RANDTAGL.JS             -->
<!--

// New taglines can be added to the end of the array (order is irrelevant).
// It is important to put line breaks <BR> in the proper places
// (to select specific tagline enter RANDTAGL?n in the TAGLINES directory,
//  where "n" is the number of the tagline from this array).

   T = new Array(0)  // Tagline array (dynamically sized; starts from "0")

   T[  1]="A man is known<BR>by the silence he keeps..."
   T[  2]="All things are difficult<BR>before they are easy."
   T[  3]="Better to understand a little<BR>than to misunderstand a lot."
   T[  4]="Beware of a half truth;<BR>you may be getting<BR>the wrong half."
   T[  5]="Doing it the hard way<BR>is always easier."
   T[  6]="Don't let your<BR>superiors know<BR>you're superior to them."
   T[  7]="Don't listen<BR>to what they say,<BR>watch what they do!"
   T[  8]="Eternal vigilance<BR>is the price of freedom."
   T[  9]="From listening<BR>comes wisdom,<BR>from speaking,<BR>repentance."
   T[ 10]="He who is good<BR>for making excuses,<BR>is seldom good<BR>for anything else."
   T[ 11]="I saw what you did<BR>and I know who you are."
   T[ 12]="If everything's coming<BR>your way,<BR>you're in the wrong lane."
   T[ 13]="If you don't stand<BR>for something,<BR>you'll fall<BR>for anything."
   T[ 14]="If you trade freedom<BR>for security,<BR>you get neither."
   T[ 15]="Liberty is from God.<BR>Liberties, from the devil."
   T[ 16]="Men fight for freedom,<BR>then pass laws<BR>to take it away."
   T[ 17]="Never argue with a fool -<BR>people might not know<BR>the difference."
   T[ 18]="Patience and time do more<BR>than strength or passion."
   T[ 19]="Professionals built<BR>the Titanic.<BR>Amateurs built the Ark."
   T[ 20]="Small is beautiful."
   T[ 21]="Spare yourself<BR>many hard falls;<BR>don't jump<BR>to conclusions."
   T[ 22]="The best lessons<BR>are learned by doing,<BR>or at least trying."
   T[ 23]="The best solution<BR>uses the fewest<BR>assumptions."
   T[ 24]="The best way to save face<BR>is to keep the lower part shut."
   T[ 25]="The scenery only changes<BR>for the lead dog."
   T[ 26]="Those who won't think<BR>will have it done for them."
   T[ 27]="Watch where you go...<BR>remember where<BR>you've been..."
   T[ 28]="We are not beaten<BR>when we loose,<BR>we're beaten<BR>when we quit."
   T[ 29]="What you don't do<BR>is always more important<BR>than what you do do."
   T[ 30]="Whenever anyone promises<BR>heaven on earth,<BR>expect hell."
   T[ 31]="Wisdom is knowing<BR>when to avoid perfection."
   T[ 32]="You can't win.<BR>You can't break even.<BR>You can't even<BR>quit the game."

//-->
  

Below is the HTML that uses RANDOM JavaScript to generate indexes for Random Tagline selection.  It gets it's URL parameters (history of previous selections — a comma-delimited list of previously selected indexes), obtains next index form RANDOM, selects and formats tagline text, and displays it along with a link for next random selection, which is in fact

The history depth (highlighted in red below) was chosen to be the minimum of 3/4 of item array size, and 60 — the standard that seems reasonable to me.  3/4 of item array size is the number of purely random attempts to generate item index, yet it might become too big for large item arrays. Absolute maximum of 60 was chosen with the presumption that each item (tagline in this example) will take roughly one minute to look at, and item repetition after approximately one hour is unlikely to be noticed (it's even more unlikely that anybody would be patient enough stay than long).



<!-- Random Tagline Sample          04/21/1998–05/14/2004 -->
<!-- ----------------------------------------- 10/14/2003 -->
<!-- www.davar.net/MISCL/TAGLINES/RANDTAGL.HTM            -->
<!-- Copyright (C) 1998–2003 by Vladimir Veytsel          -->

<HTML>
<HEAD>
  <TITLE>Random Tagline Sample (Miscellaneous Selection at Davar Web Site)</TITLE>
  <META HTTP-EQUIV="Content-Type" CONTENT="Text/HTML; CharSet=ISO-8859–1">
  <META NAME      = Description
        CONTENT   ="Page: Random Tagline Sample.
                    Site: Davar Web Site,
                          Computer Science, Programming, Mainframe, Client/Server, PC, Internet,
                          Mathematics, Go, Zen, Quotations, Extracts, Humor, Russian.">
  <META NAME      = Keywords
        CONTENT   ="Davar Web Site, Tagline, Taglines, Random">
  <META   NAME    = Author CONTENT="Vladimir Veytsel">
  <SCRIPT LANGUAGE= JavaScript SRC="../../RANDOM.JS"></SCRIPT>
  <STYLE TYPE="Text/CSS">
    A:HOVER {COLOR:Red; BACKGROUND:#FFFF66}
  </STYLE>
</HEAD>

<NOSCRIPT>
  <BODY BGCOLOR=White TEXT=Black LINK=Blue ALINK=Fuchsia VLINK=Purple>
</NOSCRIPT>
<SCRIPT LANGUAGE=JavaScript>
  <!--
    N=Math.floor(Math.random()*9)%9+1
    document.write("<BODY BACKGROUND='../../PAPER",N,"00.JPG' BGCOLOR=White TEXT=Black LINK=Blue ALINK=Fuchsia VLINK=Purple>")
  //-->
</SCRIPT>

<SCRIPT LANGUAGE=JavaScript SRC="RANDTAGL.JS"></SCRIPT>

<!-- Page: Random Tagline Sample.
     Site: Davar Web Site,
           Computer Science, Programming, Mainframe, Client/Server, PC, Internet,
           Mathematics, Go, Zen, Quotations, Extracts, Humor, Russian. -->

<FONT FACE="Times New Roman" SIZE=3>
  <CENTER>
    <I>
      <NOSCRIPT>
        <BR>
        <TABLE ALIGN=CENTER CELLPADDING=10 BORDER=2>
          <TR>
            <TD ALIGN=Center>
              Sorry,<BR>
              Essential functionality of this page<BR>
              depends on availability of JavaScript.<BR>
              Your JavaScript is either disabled,<BR>
              or not supported by your browser.</TD>
          </TR>
          <TR>
            <TD ALIGN=Center>
              Please <A HREF="../../ABOUT.HTM#JavaScript"><FONT COLOR=Red><BLINK><B>enable</B></BLINK></FONT></A> JavaScript<BR>
              and [<FONT COLOR=Red>Reload</FONT>] this page,<BR>
              or use [<FONT COLOR=Red>Back</FONT>] to <FONT COLOR=Red>exit</FONT>.</TD>
          </TR>
        </TABLE>
      </NOSCRIPT>
      <SCRIPT LANGUAGE=JavaScript>
        <!--
          Total=T.length-1  // Current total number of items in the tagline array

          Ind_Hist=location.search.substr(1)  // Get parameters passed after URL
          Ind_Hist=RANDOM(Ind_Hist,Math.min(Math.floor(Total/4)*3,60),Total)  // Get new Index History
          New_Ind =Ind_Hist.substr(0,Ind_Hist.indexOf(","))

          Letter=T[New_Ind].substr(0,1)
          Text  =T[New_Ind].substr(1)

          Tagline="<BLINK><FONT COLOR=Red><B>Next</B></FONT></BLINK>"
                 +"<A HREF='RANDTAGL.HTM?"+Ind_Hist+"'><BR>Random tagline sample</A>"
                 +"<BR> "
                 +"<TABLE BORDER=5 BORDERCOLOR=Gray CELLPADDING=30 BACKGROUND='../../PAPER0"+N+"0.JPG'>"
                 +"  <TR><TD><CENTER><I><FONT SIZE=7><FONT COLOR=Red><B>"+Letter+"</B></FONT>"+Text+"</FONT></I></CENTER></TD>"
                 +"  </TR>"
                 +"</TABLE>"
          document.write(Tagline)
        //-->
      </SCRIPT>
      <BR>
      <FONT COLOR=Green>Go to:</FONT>  <A HREF="../../index.htm">Davar site entry</A>
      <FONT COLOR=Green>|</FONT> <A HREF="../../CNT.HTM">Site contents</A>
      <FONT COLOR=Green>|</FONT> <A HREF="../../IND.HTM">Site index</A>
      <FONT COLOR=Green>|</FONT> <A HREF="../MISCL.HTM">Miscellaneous</A>
      <FONT COLOR=Green>|</FONT> <A HREF="TAGLINES.HTM">Tagline selection</A>
    </I>
  </CENTER>
</FONT>
</BODY>
</HTML>
  

To see how the RANDOM JavaScript works you may try the following:


View Random Tagline page       View [and save] RANDOM.TXT text
(Use [Back] button or [Alt]+[CL] to return here from the viewed page/text)
To make text executable rename it to *.JS and make a global change of "&lt;" into "<" signs.
Copyright © 1998–2003 by
Go to:  Site entry | Site contents | Site index | Internet | JavaScript | Text top