0% found this document useful (0 votes)
21 views5 pages

CS3157 Lab 4: Magic Square in C

This document provides instructions for a lab assignment involving programming in C and shell scripting. It outlines 4 steps: 1) Developing code to generate and check random magic squares in C. 2) Modifying the code to repeatedly permute squares until a magic square is found. 3) Creating a CGI program to run the magic square code via a web page. 4) Writing a shell script to analyze a data file and output statistics using UNIX commands.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

CS3157 Lab 4: Magic Square in C

This document provides instructions for a lab assignment involving programming in C and shell scripting. It outlines 4 steps: 1) Developing code to generate and check random magic squares in C. 2) Modifying the code to repeatedly permute squares until a magic square is found. 3) Creating a CGI program to run the magic square code via a web page. 4) Writing a shell script to analyze a data file and output statistics using UNIX commands.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

cs3157 Advanced Programming Summer 2006, lab #4, 30 points June 15, 2006

Follow these step-by-step instructions. This lab must be submitted electronically (see instructions at the end of the lab) by Wednesday June 21, 4 pm. You need to include a README file with information about each file submitted and any other comments you want the TAs to see. You are required to create a single Makefile to run each of the steps of the lab. (Example, make step1 should compile and run step1 of the lab.) In addition you need to have a make clean step to clean up the object files, and executables generated by your make steps. Feel free to add comments to your makefiles

Step 1 Magic square in C ! (10 points)


In this step, you will develop code that computes a magic square. A magic square is a 3 by 3 matrix filled with integers in the range [1 - 9] so that each entry in the matrix has a unique value. The sum of each of the rows and each of the columns and each of the two diagonals must be equal to 15. (Note that there is not a single solution to the magic square problem.) Remember that you are still working in c. Create a file called Maintest1.c/Magicsquare1.c/Magicsquare1.h and (to help you get started ) start by putting the following code/declarations in each file (where appropriate): #include <stdio.h> #include <stdlib.h> #include <time.h> typedef int MSQUARE_TYPE[3][3]; typedef MSQUARE_TYPE * MagSquare_PTR; void initSquare( MagSquare_PTR ); void printSquare( MagSquare_PTR ); int main() { MagSquare_PTR mptr= /* replace with something with malloc */; srand( time( NULL )); initSquare( mptr ); /* add comment for this */

/* will setup a random magic square */

printSquare( mptr ); /* will print out a square */ } // end of main()

Define the function initSquare(MagSquare_PTR) which takes the magic square pointer argument (as above) and fills it with values in the range [1 - 9]. These values must be assigned RANDOMLY, but make sure that no number appears more than once in the array. Also Define the function printSquare(MagSquare_PTR) which takes the magic square pointer argument (as above) and prints out its contents to the screen in a nice 3 rows by 3 columns format. You should test your code with just these 2 functions to make sure each is working (before adding the rest of the functions). Hint: To get random numbers look up lookup rand() and srand() from the stdlib libary. 1. maintest1.c this will contain the main function 2. magicsquare.h this will contain the functions declarations that you will be using. 3. magicsquare.c this will contain the function definitions from above including the following methods: a. void initSquare(MagSquare_PTR) (see above) b. void printSquare(MagSquare_PTR) (see above) c. int sumColumn( int column, MagSquare_PTR ) The function takes the 2-dimensional magic square array and a column number and returns the sum of the 3 values in that column d. int sumRow(int row, MagSquare_PTR) see above. e. int sumDiagonal( int diagonal, MagSquare_PTR ) The function takes the 2-dimensional magic square array and a diagonal number and returns the sum of the 3 values in that diagonal. Use diagonal = 0 to refer to the diagonal that runs from the northwest corner down to the southeast corner. Use diagonal = 1 to refer to the diagonal that runs from the northeast corner down to the southwest corner. f. Create a function called int isMagic(MagSquare_PTR) which takes the magic square pointer as an argument and checks each of the rows and columns and diagonals to see if all the sums equal 15. The function should return 0 if the argument is not a magic square and 1 if it is a magic square. g. Modify the above main() so that it calls isMagic() and prints out whether the square is a magic square or not. h. Modify the main() program so that after it prints out the square, it computes (using the functions above) and prints out the sum of each of the 3 rows and each of the 3 columns and each of the 2 diagonals. Compile and test your program. Here's a sample output:
the square is not a magic square here is your square: 2 8 3 1 4 5 7 9 6 sum of row 1 = 13 sum of row 2 = 10 sum of row 3 = 22 sum of column 1 = 10

sum sum sum sum

of of of of

column 2 column 3 diagonal diagonal

= = 0 1

21 14 = 12 = 14

Step 2 get the square (8 points)


Now copy maintest1.c to maintest2.c and magicsquare1.c to magicsquare2.c, and magicsquare1.h to magicsquare1.h modify them as follows: 1. Create a function called permuteSquare(MagSquare_PTR) which takes the magic square pointer as an argument and randomly switches two entries in the array. Do this by randomly picking two sets of row and column indices (in the range [0 - 2]) and then swapping the entries located at each pair of indices. Check to make sure you arent picking the same spot .. that is swapping the same location with itself 2. Modify the main() so that after it calls isMagic(), if the square is not magic, then it calls permuteSquare() to switch around two entries in the square and then test again to see if the square is magic. Do this repeatedly until a magic square is found. When a magic square is found, call printSquare() again to print out the magic square. 3. Have the program count the number of times it has to permute the square in order to find a magic square. Print that out too (Hint: count it where you call method permutesquare). Remember this can take a while. Compile and test your code.

Step 3 CGI (4 points)


CGI! Create a file called maintest3.c and [Link] which together allow your program to over the web. The html page should provide some information on what a magic square is, and allow the user to click on a button to get started. The program should run as in the previous step, and then output an html page with all the information (you should put the magic square values in an html TABLE tag (look it up if necessary). Also you need to time the running time of your program so output the time when the program was called, and how long it took to get the correct answer. Remember that to run a cgi c program you need to perform the following steps: 1. code your c program 2. successfully compile the c program on the correct platform..you will probably run it from your own desktop. For cygwin, it means compiling a exe file and having cygwin in your path to get it to run. 3. rename the executable to [Link] and call it from a webpage locally (make sure its executable). 4. you can also test the cgi script separately, by running it on the command line. Here is a sample c CGI program:
#include <stdio.h> #include <stdlib.h> int main() { printf( "Content-type: text/plain\n\n" ); printf( "QUERY_STRING = [%s]\n",getenv( "QUERY_STRING" ));

} // end of main()

to get the time:


#include <stdio.h> #include <sys/types.h> #include <time.h> main() { time_t t1,t2; (void)time(&t1); printf(current time is %s,ctime(t1));

Shell Programming Section. In this lab, youll use several UNIX tools which we discussed in class on Wednesday. The tools are: cut outputs sections of each line in input grep outputs lines matching a pattern sed stream editor sort outputs sorted concatenation of input wc outputs the number of bytes, words and/or lines in input ps outputs process id of all running processes The man pages for each of these can be accessed by typing, for example man cut, at the UNIX prompt. We mentioned (briefly), how send the output of these commands to a file as well as to stdout (which is the default). We also discussed how you can pipe the output of one command into the input of another. Heres an review/overview in brief: The greater-than sign > is used to redirect the output of a command from stdout to a file. This is like opening a file for writing in C. If the file exists, it will be overwritten. If the file does not exist, then it will be created. Heres an example: grep "hello" myfile > [Link] This example will search for all lines containing the word hello in a file called myfile, and it will output those lines (containing the word hello) to the output file [Link]. The double greater-than sign >> is used to append the redirected output to the end of an existing file, rather than creating a new file. If the file does not exist, then it will create it. This: grep "hello" myfile >> [Link] will behave just like the example above, except that the output will be added to the end of the [Link] output file. The vertical bar | is used in between commands to pipe the output of the first command into the input of the second command. For example: grep "hello" myfile | wc -l will look for all the lines in myfile that contain the word hello and will output those lines, but instead of outputting them to the screen, the lines will be read as input by the wc command, which (since it is invoked with the -l option) will output the number of lines it receives.

Step 4 Getting Statistics from a file (8 point)


Create a Bourne shell (/bin/sh) script file called [Link]. The shell script should use the above UNIX commands to print out statistics from the file [Link], answering the questions below. Label each of the statistics output. Hint: you can use the echo command in a shell script to print text to the screen, for example: echo hello world to view the contents of the file you can type either of the following commands: more [Link] less [Link] 1. How many movies are in the data file that are being shown in the evening ? By morning, I mean any movie whose starting time is listed as PM. It doesnt have to be a unique list if one movie is shown three different times during the month, you should then count that movie 3 times. 2. How many movies are in the data file all together ? Again, it doesnt have to be a unique list if one movie is shown three different times during the month, you should then count that movie 3 times. 3. How many times did John Wayne appear in a movie on TCM in February ? If the same movie is shown twice, then count it twice. You can safely assume that John Wayne is the only actor listed in the file whose name contains Wayne. 4. How many movies made in the 1940s are in the data file ? 5. How many movies were not made in the 1930s in the data file ?

Submit your lab.


See instructions online

Common questions

Powered by AI

In Python, direct functions similar to rand() and srand() in C are readily available through the standard random library, specifically random.sample or random.shuffle for generating unique random sequences, simplifying unique integer assignment. Python lists could easily handle dynamic data size adjustments, reducing pointer complexity seen in C. Interactive development through Python's REPL would expedite iterations. Moreover, Python's strong library support could streamline matrix manipulations and web integration, contrasting the manual setup for CGI in C.

The transformation involves first checking if a randomly filled 3x3 matrix is a magic square using the function isMagic(). If not, the process involves repeatedly calling permuteSquare(), which randomly swaps two entries in the matrix. This permutation is tested after each swap using isMagic() until the matrix meets the criteria of a magic square. The process continues iteratively until a magic square is successfully formed.

A "magic square" in this context is a 3x3 matrix filled with unique integers from 1 to 9 such that the sum of each row, each column, and both diagonals is equal to 15. Its validity is determined programmatically using the function int isMagic(MagSquare_PTR), which checks that all these sums are equal to 15. If they are, the function returns 1, indicating a valid magic square; otherwise, it returns 0.

UNIX shell commands can process and analyze film data by redirecting output, piping commands, and using specific utilities. For instance, grep filters content to find movies shown in the evening ("PM") or features with certain criteria, like 'John Wayne'. Combined with wc, it can count occurrences or appearances. Specific statistics retrievable include the number of evening showings, total movies listed, John Wayne's appearances, and the count of films from a specific era like the 1940s.

The sample outputs demonstrate that the program can identify whether the matrix is a magic square by checking if the sums of rows, columns, and diagonals match the target sum of 15. These outputs capture the sums for diagnostic purposes, showing calculations per row, column, and diagonal, and verifying if the current configuration meets magic square conditions. The verification process handles variability, reflecting iterative attempts until the correct configuration is achieved.

The srand function seeds the pseudo-random number generator, initializing it to produce different sequences of numbers each time the program is run, whereas the rand function generates random numbers each time it is called. In the context of the magic square, these functions collectively help fill the square with unique random numbers between 1 and 9, ensuring variability and unpredictability in the initial matrix configuration.

HTML and CGI are used to present the results of the magic square computations on the web. HTML provides the structure and interface for user interaction, containing informational text and buttons to initiate the magic square generation. CGI scripts executed on the server generate magic squares, then dynamically update HTML content to display these results, including statistical calculations like execution time. This setup allows non-terminal users to interact with the C-based program easily via a web browser.

The initSquare function initializes the magic square by filling it with unique, randomly assigned integers from 1 to 9. This lays the foundation for generating a random magic square that meets the non-repeating criteria. The printSquare function then takes the pointer to this filled magic square and outputs its values in a 3x3 format, allowing for easy visualization and verification of the matrix's configuration.

Challenges include managing memory allocation and deallocation to avoid leaks, using secure CGI implementations to prevent injection attacks, ensuring portability across different system architectures for consistent program execution, and correctly parsing input from both command-line and web environments. Additionally, careful handling of file permissions and execution rights is necessary for secure web server integration. Error-handling mechanisms must be robust to gracefully recover from unexpected input or failures without causing undefined behavior.

Redirection in shell scripting allows the output of one command to be saved into a file using '>', enhancing workflows by preserving results for later review or further processing. For instance, filtering lines with grep and saving results helps track specific data points across commands, like movie titles projected during a certain period. Appending '>>' maintains cumulative statistics without overwriting files. These redirection techniques streamline file analysis, reducing manual data handling and organizing outputs.

You might also like