Mathematics 152
Project 1
A PHP Program to Multiply Permutations

The initial user-interface design for this project was done by Carli Collins, a Harvard Extension School graduate student.  Testing the whole project, including extra-credit features, was accomplished by Zoltan Feledy, also a Harvard Extension School graduate student.

This project assumes that you have experience at programming in some language: C, C++, Basic, Java, Perl, JavaScript ....  You will learn PHP and a little bit of HTML as you go.

Construction of this project proceeds in three stages. The first two can be done in either order, since they are independent of one another,
I. Create the user interface.   This is a form on an HTML Web page that can be displayed in any browser.   All you have to do is to follow instructions, but in the process you will learn a bit about the design of pages.  You will have the option to add new features to the form, but this can be done by copying what you have learned how to do. 
If you are not interested in learning how to create Web pages, you can skip this step and do only step II, for substantial partial credit..
II. Implement the mathematics.  This requires you to write functions in PHP that operate on character strings to produce other character strings.  The fact that the output is displayed in a Web page is irrelevant.   Since this is a mathematics course, your major task will be to rewrite these functions so they work in all cases.
III. Accept input and process output.  PHP is a "server-side" language.  This means that the user of the browser (the "client") enters data that is sent over the Internet to your computer (the "server").  The server does some calculations and rewrites the original Web page to display the results.  For the most part you will learn to do this just by following instructions. You will have the option to display the results of additional calculations on the form, but this can be done by copying what you have learned how to do.

Suggested schedule:
After the first class, install PHP according to the accompanying instructions.
After the second class, follow the instructions in this document for part I.
During the second week of the course, complete the project.

What to do if you get stuck.
Test frequently.  PHP, while excellent in many regards, does not have good debugging facilities.  On the other hand, it takes only a couple of seconds to see the effect of a change in your code.
If you are not sure of the value of a variable (named $power, for example) in your PHP code, a statement like "echo $power" will print it out at the top of the Web page.
If you have done your best to follow directions yet are stuck for more than 15 minutes, the best thing to do is to email your .php and .css files to bamberg@tiac.net. On Tuesday, Wednesday, or Thursday morning or Tuesday evening,  you can come to Quincy 102 and participate in debugging.  During the rest of the week you can perhaps get a bug fix by email.

 

 

I. Create the User Interface

 

1.      Open HapEdit. From the menu, choose Project...New...Create Project. A dialog box will appear, allowing you to select a folder. Click the icon to the right of "Create in folder," and navigate to C:\EasyPHP\www\.  Create a project name by concatenating "M152" and your name; for example M152Bamberg.  A folder icon labeled "M152Bamberg" will appear in the right pane (but here and elsewhere, it will have your own name instead of "Bamberg.")    Double click on it, and then click on the Documents icon in the toolbar.

 

2.      From the File menu select New...PHP Page, and save this page as M152Bamberg/permute.php

 

3.      Change the title tag of your document to Permutations by <Your Name>, for example

<title> Permutations by Paul Bamberg</title>

 

4.      Creating a large centered header:
a. Place the cursor immediately below the <body> tag, then choose Actions...Text...Insert Paragraph from the menu. This will generate a pair of tags.  It's a safe way to generate HTML tags, since they are guaranteed to be correct and balanced.  Type some text between the tags to start your page, such as:

<p>Multiplying Permutations</p>
At any time you may press F9 to see how this PHP will display as a Web page. Do this now. If asked about a URL association, choose http://localhost/M152Bamberg. Close your browser to get back to editing.
b. Change the paragraph to a header, remembering to change both the opening and closing tags:
<h2>Multiplying Permutations</h2>
Press F9 again to see more impressive results. Try h3 or h1 instead of h2 to get different sizes.
c. Highlight this header and choose from the main menu Actions...Text...Align text...center...OK. Press F9 again.
Thanks to the editor, you don't need to memorize the HTML syntax for centering text.

 

5.  Inserting a form:

    1. Place the cursor just above the closing </body> tag, and Select Actions-Form-Insert Form from the menu
    2. Name the form permutations, set the action to  permute.php, and leave the Method as Post. Click OK.  The effect of the action will be, when the user clicks a button, to submit the data that has been entered back to this PHP file for processing.

 

6.  Creating a table:
Here is a simple plan for laying out the form.  The cells marked "reserved for" will be your job.

 

Row 1, Cell 1 (input)
Row 1, Cell 2 (powers of a)
Row 1, Cell 3 (powers of b)
Row 2, Cell 2 (products)
Row 2, Cell 2 (reserved for powers of a*b)
Row 2, Cell 3 (reserved for powers of b*a)
Row 3, Cell 3 (reserved for inverses)
Row 3, Cell 3 (reserved for conjugates) Row 3, Cell 3 (button)


    1. Put your cursor between the form tags, and select Actions-Table-Insert Table… from the menu. On the Frame tab set border to 1, spacing to 3, and margin to 3 and click OK. Your code should now look like this:

<table width="100%" border="1” cellpadding="3" cellspacing="3>

               b. Put your cursor between the <table></table> tags, then select Actions ...Table...Insert Cells… from the menu. Select the Cell tab and input 3 into # of cells and 3 into # of lines. You will see the html for three empty rows, each with three empty cells.
               c. In Row 1, Cell 1 (top left), denoted by a  <td></td> tag, insert a paragraph tag by selecting Actions...Text...Insert Paragraph and type in ‘Permutations’ between the <p></p> tags.
    1. In the same cell, on the next line, insert a paragraph tag, Between the tags, type a and then insert a text field by selecting Actions...Insert Form...Insert Text Field, Set the name to aText and click OK. As a placeholder, provide the value (12).
    2. In the same cell, on the next line, insert a paragraph tag, Between the tags, type b and then insert a text field by selecting Actions...Insert Form...Insert Text Field. Set the name to bText and click OK. As a placeholder, provide the value (13). You should now have
      <td width="100%">
                 <p>Permutations</p>
                 <p>a <input type="text" name="aText" value="(12)" size="20" /></p>
                 <p>b <input type="text" name="bText" value="(13)" size="20" /></p>
       </td>
      Press F9 to see what this cell looks like.
    3. In Row 2, Cell 1, insert a paragraph tag and type a*b=(132) between the tags.
      In the same cell insert a paragraph tag and type b*a=(123) between the tags.
      Press F9 to see what this cell looks like.
    4. In Row 1, Cell 2, insert a paragraph tag and type Powers of a.
      Then use Actions...Insert Form...Insert Textarea to insert a text area named powersA, with two lines of text, (12) and I.
      Press F9 to see what this cell looks like.
    5. In Row 1, Cell 3, insert a paragraph tag and type Powers of b.
      Then use Actions...Insert Form...Insert Textarea to insert a text area named powersB, with two lines of text, (13) and I..
      Press F9 to see what this cell looks like. 
    6. In Row 3, Cell 3, insert a button by selecting Actions...Form...Insert button. Type in Calculate for the name, check Provide value and type in Calculate. Click OK. The button code should be as follows: <input type="submit" name="Calculate" value="Calculate" />.
      Press F9 to see what this cell looks like.
      Experiment with resizing your browser window to see that the overall page layout continues to look reasonable.
      Now that all the elements are in place you may wish to set the table borders to 0.  This is a matter of taste.

7. At this point, you could fill in the four remaining cells, but it is probably simpler to wait until the very end.  That way you can do without placeholders.

 Applying a Cascading Stylesheet (CSS) to the User Interface
You may apply a style to any HTML elements such as tables, table cells, table rows, button, horizontal rules or to the Body tag. The preferred way to do this is by putting the style sheet in a separate file. This is especially efficient if you want many pages to share the same style. If you put the style sheet in a separate file, all pages can point to it.

 

If you have not already done so, download and install TopStyle 3.10 Lite Trial version from http://www.bradsoft.com/download/index.asp.
Click on the link to download the TopStyle Lite 3.10 (Free) link. Save this file to your file system and follow the installation instructions.


8.
Launch TopStyle Lite. It will open a New CSS document for you.
Create the style sheet by typing in the following.  The editor will help you select what is to the left of each colon.
The values of the form #99ccff specify colors, with red, green, and blue values in hexadecimal (00 minimum, ff maximum).  You can experiment with changing them.
Values of the form 11px specify sizes in pixels. You can experiment with changing them.
For font-family, there is a list of fonts to guard against the possibility that the first choice (Verdana) is not available on the user's computer.

Save this file as math152.css in your project directory (C:\EasyPHP\www\M152Bamberg). If you email the project for grading, you must remember to include this file, but it will be simpler to zip up the entire directory.

 

.table {  
  color: #00008B;    
  font-family: Verdana, Arial, Helvetica, sans-serif;  
  font-size: 11px;
  font-weight: bold; 
  text-align: left; 
}
 
.button {
  background-color: #99ccff;
  border-bottom: #003399 solid 1px;
  border-right: #003399 solid 1px;
  border-left: #99ccff solid 1px;
  border-top: #99ccff solid 1px;
  color: White;
  font-family: Verdana, Arial, Helvetica, sans-serif;
  font-size: 11px;
  font-weight: bold;
  padding-left: 3px;
  width: 150px;
}

 


9.  Open your permute.php file in HapEdit and add a link to your style sheet. First place your cursor between the  <head></head> tags, under the <meta> tags. Type in
   <link rel="stylesheet" href="math152.css">

       You can now use the button class and table class that are defined in the style sheet.
       Apply the button class to the Calculate button by typing in class="button". Your code should now look like this:

<input type="button" name="Calculate" value="Calculate" class="button">
Now add the table class to the table and see how all the text changes. Add class=”table” in the opening table tag like this:

<table width="100%" border="0" cellpadding="3" cellspacing="3" class="table" >


Press F9 to see what the Web page now looks like.  You should see a dramatic difference.
When you show your finished project to friends and neighbors, they are more likely to be impressed by the appearance of your user interface than by your clever algorithm for multiplying permutations.


II. Implement the mathematics
10. Now we get to the real business of this project, which is to work with permutations.  Since in a later project it will be useful to be able to multiply permutations, we will put the mathematical code in a separate file.  Using File...New...Text, create a new file called permutecalc.php.  This will contain only php code.  As the first line, use <?php, and as the last line, use ?>.
The first function that you will need to write is one that treats a permutation as a function.  A reasonable name is Apply.  This function will take two string arguments, a permutation like "(134)" and a symbol in the range "1"..."9" and return the character that represents the effect of the permutation on the symbol.  So, for example,
Apply( "(134)","1") returns the value "3".
In order to write and test this, include test code in permutecalc.php, so it starts as
<?php
function Apply($perm, $input) {
    if ($perm == "I":)
        return $input;


}


echo Apply("I", "2"),"<br>";
?>


This has the nice feature that it is correct for the identity permutation, so that it will produce correct output as written.
It is your job to write this function and test that it works in all cases. Study Example 6-3 in the online manual to learn how to inspect individual characters in a string.
Look at string functions in the online manual, especially strpos(), strrpos(), and substr().  Once you can process (14)(257)(68) and determine that "7" ends a cycle that starts with "2," you have done the hardest step.


11. Once you have the Apply function written and tested, get to work on the Multiply function.  Multiply($second, $first) should return the permutation that is the result of $first followed by $second..  It can start like this:
function Multiply($second, $first) {

 if ($second == "I")
             return $first;

 if ($first == "I")
             return $second;

 $result = "";
//your code goes here

 if ($result == "")
             return "I";
}

Here is a good strategy:
   Initialize an array to mark the characters "1" though "9" as all unprocessed.
   For all characters $c from "1" up through "9" {
       if the character is processed, move on using continue;
       if Apply($second, Apply($first, $c)) returns its input, move on using continue;

find the complete cycle that starts with $c, marking characters processed as they occur;
   }     


C programmers will find one issue tricky.  To convert a character $c to the next one in sequence, you must use
chr(ord($c)+1)


Test this function with lines at the bottom of the file like
echo Multiply("(1236)(45)", "(123)(457)");
until it works in all cases.


12. Next we need a function to display powers of a permutation.  The result will be displayed in a textarea.  This means that to get a line break, we need to use the character "\n" (newline).
Here is a function that returns precisely the string that needs to be displayed.  Notice the use of the period to concatenate strings in PHP.
function PowerString($perm) {
    $power = $perm;
    $result = $perm;
     while ($power != "I") {
          $power = Multiply($power,$perm);
          $result = $result."\n".$power;
     }
    return $result;
}



13. You will eventually need a function Inverse($perm), so write and test it now. A tip on writing this:.
The PowerString function, already provided, is correct in the general case.  At the step just before you calculate the identity, you have found the inverse.  In other words, if a permutation a has order n, then an-1 is the inverse of a.
It might also be worthwhile to write and test a function Conjugate($a, $b) that calculates a b a-1. At this point the mathematics is complete, and you should get no mathematical errors while calculating and displaying output.



III. Connect the mathematics with the HTML
14. Once permutecalc.php is fully tested, you have two choices.  Either submit it for partial credit, with all the test code included, or comment out the test code by putting /* before it and */ after it, and include it in permute.php with the line

include_once("permutecalc.php")

immediately under the opening 

<?

15. When your PHP program executes, it must first simply display the HTML form. Then the user will type permutations into your two text fields aText and bText and press the Calculate button. At this point the values typed into the form are submitted to the PHP program, which must calculate and display the results.


When the "submit button" (Calculate) is pressed, all the values in the form show up in a PHP global array named $_POST, and your first task is to save them into PHP variables, allowing the possibility that they are undefined because the form is being displayed for the first time.
So immediately under the include statement, type

$Astring = isset($_POST['aText'])?$_POST['aText']:"";

$Bstring = isset($_POST['bText'])?$_POST['bText']:"";
Displaying the correct output is simply a matter of writing php code to replace text strings and display the correct values. For a start, modify Row 1, Cell 1 to read
 <p>a <input type="text" name="aText" size="20" value="<?php echo $Astring; ?>" /></p>
 <p>b <input type="text" name="bText" size="20" value="<?php echo $Bstring; ?>" /></p>
Be sure you understand what is happening.  The first time the program is run, the values of aText and bText have not been specified.  The isset() function of PHP detects that the variable $_POST['aText'] has no value, and it makes $Astring be the empty string, which is of course the right value to display.  Once the user has clicked the Calculate button, the values that the user enters get stored in $Astring and $Bstring, and we need to redisplay them, since we are re-creating the whole Web page from scratch.
Press F9 and verify that whatever permutations you enter get redisplayed.  If this works, you have overcome the hurdle of communication between client and server, and everything else will be straightforward.


16. To display the result of multiplication, change Row 2, Cell 1 to read
          <td width="100%">
            <p>a*b = <?php echo Multiply($Astring, $Bstring); ?></p>
            <p>b*a = <?php echo Multiply($Bstring, $Astring); ?></p>
          </td>

Press F9 and test the program.
17. To display the calculation of powers, change Row 1, Cells 2 and 3 to read

       <td width="100%">
           <p>Powers of a</p>
           <textarea name="powersA" rows="4" cols="20"><?php echo PowerString($Astring); ?></textarea>
         </td>
         <td width="100%">
           <p>Powers of b</p>
           <textarea name="powersB" rows="4" cols="20"><?php echo PowerString($Bstring); ?></textarea>
         </td>

 Press F9 and test the program with various inputs.
18. The rest is up to you.  Here are the tasks, with point values. Notice that you can get 5 points for part II alone
The basic HTML form from part I: 2 points
Write Apply () and Multiply() so that they correctly calculate the product of any two permutations involving the symbols "1" through "9." : 4 points
Write the Inverse() function: 1 point
Display products and powers correctly: 1 point
Display the inverses of a and b: 2 points.
Calculate and display the "conjugates" a b a-1 and b a  b-1: 1 point.
Grading will be based only on correctness.  If your program runs correctly, no one will need to look at your source code. This means that if you know your computer's IP address, you can just email Paul Bamberg (bamberg@tiac.net) a link to your php file.  Otherwise email him your php files and your style sheet file, or zip up the entire directory and email it.
Here are some items for extra credit:
Make some interesting-looking changes to the appearance of the program by modifying the CSS file: 1 point.
Deal somewhat gracefully with incorrect input: 1 point