Computing index
EXAMPLE 2
PASCAL'S TRIANGLE

[ Example 1 | Example 2 | Example 3 ]


Before reading on you may first want to
  • Use the script - if you have never used the script before.
  • View the script - to see the script in a fresh window to refer to as you read this guide.



What the script does

    The Pascal's triangle script was really an experiment in background running and opening windows in javascript. The script is really quite useless and I'm not sure why it's as popular as it is!

    When operated, the script opens a window and inserts black and white boxes (2x2 pixels) which form the triangle required with a given number of rows. The boxes should be inserted a few at a time, allowing control of the browser to pass back to the user every so often. The actual calculation of Pascal's triangle is overwhelmed by the variables and commands that synchronize the process.



User input

    The script needs two input values: the number of rows to display and a divisor value which alters the pattern.

    These values will be taken from two text input boxes:

<input type="text" size=3 name="depth"  value="63">
<input type="text" size=2 name="factor" value=" 2">
    which specify the depth and factor of the triangle respectively.



Program variables

    Clearly each row in the triangle is made up of a sequence of numbers, so to store these numbers we need an array:

curvals = new Array()

    A variable called ProcessingTri is used to indicate when the script is processing a triangle.
ProcessingTri = false
    This is needed because we calculate the triangle in the background. This means as control of the browser returns back to the user, the user may repeatedly click on the submit button whilst we are still processing a triangle.
    By setting the ProcessingTri variable to true as we begin the calculations and then back to false when we finish, we can prevent multiple processes operating on the same values in the curvals array.



How the script operates


    The triangle is created by one function which takes three parameters.
    The first two parameters are from the user input form - depth and fac. The third (pstage) indicates the current row of the triangle we are processing, and the operations performed by this one function depend on this value.


1.   Starting up the process

    The CreateTriangle function is called from the button in the HTML form. This is the first call to the function and pstage is set to 0.
    The script detects that pstage is zero and performs the following tasks:

  • If we are already processing a triangle, exit the program and do nothing.
    if ( ProcessingTri )
    	return
    
  • Calculate the width and height of the window needed to display all the rows in the triangle. These values are then converted to strings so we can use them when we define the window (see next task).
    wstr=((dep*2)+75).toString()
    hstr=((dep*2)+175).toString()
    
  • We then define a new window which can be resized by the user but has no toolbar, status bar, menubar or scrollbar and has the width and height calculated previously.
    trianglewindow = window.open("", "",   "resizeable=1,
    					toolbar=0,
    					status=0,
    					menubar=0,
    					scrollbars=0,
    					width="+wstr+",height="+hstr)
    
        A short-cut is also defined here. triwin saves us having to type trianglewindow.document whenever we want to write something in the window.
    triwin=trianglewindow.document
    
  • Next we insert some HTML code into the window, entering code just like we would normally use in a HTML file.
    triwin.write("<html><title>Pascals Triangle (Div='+fac.toString()+')</title><body bgcolor='#000000' text='#c0c000'><p><br><center>")
    
    triwin.write("<p><font size=2>close this window
    before opening a new<br><form><input type='button' value=' CLOSE ' onClick='window.close()'></form><p>")
        The second write statement inserts a small HTML form in the window, which displays a button that quits the window when the user clicks it.

  • We now set ProcessingTri to true:
    ProcessingTri = true
    
  • Finally - the important bit. We now want to call the CreateTriangle function to process the first row in the triangle. The setTimeout method allows us to do this but after a short delay. Without this delay the user would not be able to operate buttons etc on his/her browser.
    TriTimer = window.setTimeout("CreateTriangle("+dep+","+fac+",1)", 20)
    
        The above command will run the CreateTriangle function, with the dep and fac values that were used in this call, after a delay of 20 milliseconds. The pstage value used will be 1, i.e. we should compute the first row in the triangle.

        Like above, the timer is usually given a name (in this case TriTimer). This is so the call can be cancelled if for some reason we want to kill the process.


    2.   Calculating the next row

        The first step is to calculate the numbers in this row from the values in the previous row:

    left = 1
    for (j=2; j<=pstage; j++) {
    	right = curvals[j]
    	curvals[j] = left + right
    	left = right
    }
    curvals[pstage] = 1
    
        The values in each row are calculated by adding the values to the left and right in the row above.
        For the first value the value above and to the left is 1.
        Running along the row, the value above and to the right is the jth value in the curvals array. So the value in this row is simply left + right. Now, as we move onto the next value in this row, the value above-right becomes the value above-left, and we repeat the cycle.
        At the end of the row we insert a 1.


        Next the script must output a sequence of black or white dots, depending on whether the value at this point is a multiple of the fac value.

        The section of code to do this is:

    for (j=1; j<=pstage; j++) {
    	if ( Round(curvals[j]/fac)==(curvals[j]/fac) )
    		cps="WhiteDot"
    	else
    		cps="BlackDot"
    	triwin.write("<img src='"+cps+".jpg'>")
    }
    triwin.write("<br>")
    
        Notice that pstage is used to count along the values in the row. This is because the number of values in a row will be equal to the number of that row.


        We now use the setTimeout method again, to call the CreateTriangle function which will process the next row in the triangle.

    TriTimer = window.setTimeout("CreateTriangle("+dep+","+fac+","+(pstage+1)+")",10)
    
        This time we leave a delay of only 10 milliseconds.


    3.   Finishing the display

        After computing and displaying all the rows in the triangle, all that remains to do is close the HTML document:

    triwin.write("</center></body></html>")
    
        call the close method to tell the browser we have finished writing to the trianglewindow:
    triwin.close()
    
        and finally set ProcessingTri to false to indicate we have finished computing this triangle.
    ProcessingTri = false
    




    [ Index Page | HTML Guide | JavaScript | Free Images | My Scripts | Resources Links ]

    ©1998 Stephen Battey
    This page hosted by Get your own free home page