Anda di halaman 1dari 10

CS

200 Introduction to Programming Assignment 2


Well done! The mere fact that youre reading this handout means that the snake assignment is behind you! In this assignment, well be doing something much less exciting, however. Were going to be dealing with getting all the nuts and bolts of C++ right, so that you are all geared for some more exciting assignments next week. The usual rules of plagiarism apply. For more details, see the handout for Assignment 1. There will be a total of 7 tasks in this assignment, and you will have to submit a separate file for each task. In addition, there are 2 Hackers Edition tasks, which can be done for extra credit.

IMPORTANT!

You must create a new cpp file for every task, and name it Task1.cpp, Task2.cpp, Task3.cpp, etc. BE VERY CAREFUL OF THE NAME AND CASE! These assignments are going to be graded by a software, and if there are any naming discrepancies, your assignment will go ungraded. NO EXCEPTIONS. This is not something extremely technical to follow. All assignment submissions will be done on LMS. Which means you must download your work from the Linux server via PSFTP and then upload it to LMS from your local drive. Excuses like Mujhe PSFTP use nahi karna aata! are laughable at best, and infuriating at worst. None of your submitted files should have a main function in them. Your functions will be thoroughly tested with OUR main function, and if any part of your code has a main function, the grader will not grade your assignment. If you want to make your own main functions to test your code, the recommended way is to make a separate file called main.cpp, and create your main function in there. You can then compile your task files and your main.cpp file together into one executable, and then run that, so when you finally submit your task files, there is no main function in them. There is a file on LMS titled Assignment2.h. This header file contains function declarations for all the functions you will be implementing in this assignment. You will need to download this file to your Linux folder and include it in every cpp file that you write. This will allow you to call functions implemented in other files from your main.cpp file. Your final submissions should not have anything else included. Please dont put this assignment off till the last moment. It is extremely lengthy, and you have only one week to do it.

If everyone scores extremely high on the assignment, the weightage for that assignment is reduced. Which means that the in-lab midterm and final weightage will increase, which we know nobody will be able to cheat in. So please do yourself a favor, and dont help out your friends, because this help will backfire on them in the midterm and final when they wont be able to code to save their lives. Please do your own work, and encourage others to do so. DC notices for cheating cases on Assignment 1 coming soon J. Seriously, look forward to them.

Task 1 Combinatorics
Write a function that takes in an integer N, and outputs the factorial of N (mathematically written as N!). For those who do not know what a factorial is, please have a look at the following link: http://en.wikipedia.org/wiki/Factorial. Your function should have the following signature: int fact(int n); A function signature is simply the name of the function, its return type and its input parameters. Once your factorial function is working perfectly, implement the following two functions: int perm(int n, int r); int comb(int n, int r); The perm function should output the total number of permutations of r objects taken without replacement from a set of n objects. The comb function should output the total number of combinations of r objects taken from a set of n objects. For those of you who do not know what permutations and combinations are, please have a look at the following link: http://www.mathsisfun.com/combinatorics/combinations-permutations.html.

Task 2 Vector Arithmetic


In this task, you will be implementing some very basic functions relating to vector arithmetic. For those of you who are taking, or have taken, a course in Linear Algebra, these functions should be self-explanatory. float magnitude(float vec[], int n); This function should take as input a n-dimensional vector, represented as an array of length n, and return the magnitude of the vector. float dot(float vec1[], float vec2[], int n); This function should take as input two n-dimensional vectors, and return their scalar product, otherwise known as dot product. These vectors are represented as two arrays of floating-point numbers, each of length n, where n is also a parameter to the function. float angle(float vec1[], float vec2[], int n); This function should take in as input two n-dimensional vectors, and return the angle, in radians, between the two vectors. You may want to use functions that you have already implemented above. void normalize(float vec[], int n); This function normalizes an n-dimensional vector, represented by an array of length n. The array passed in as an argument should be modified such that its magnitude should become 1, but its direction should not change. Note that this function does not have a return value. When an array is passed to a function, it is passed by reference. Which essentially means that if an array is modified inside a function, then its results will be visible to the function that called it as well. void cross(float result[3], float vec1[3], float vec2[3]); This function should take in as input three arrays of floating point numbers, with each array of length 3. This function should compute the cross product vec1 x vec2, and store it in the result array passed as the first argument. This function should not declare or allocate memory for the result array this is the job of the function that calls the cross function. The cross function will only modify the contents of the result array.

Task 3 - Geometry
This task will require you to implement some basic geometric functions. bool intersect(float l1[2][2], float l2[2][2]); This function takes in two two-dimensional arrays, each of size 2x2. l1 contains the coordinates of line segment 1, and l2 contains the coordinates of line segment 2. In both matrices, the following scheme is followed: The first row contains both x and y coordinates of the first endpoint. The first column contains the x-coordinates of both endpoints. The function should output true if the line segments intersect, and false otherwise. float area_overlap(float rect1[4], float rect2[4]); This function should take in two arrays, each of length 4, which represent two rectangles. In both arrays, the first element is the x-coordinate of the bottom-left point of the rectangle, the second element is the y-coordinate of the bottom-left point of the rectangle, the third element is the width of the rectangle, and the fourth element is the height of the rectangle. This function outputs the area, if any, which is covered by both rectangles, as a floating point number. If the rectangles do not overlap, the area should be zero. float polygon_area(float arrX[], float arrY[], int n); This function computes the area of a polygon with n vertices. Assume that the polygon does not intersect itself. The coordinates of the polygon are passed to the function via two arrays of length n. The first array contains the x-coordinates, and the second array contains the y-coordinates of the points. The area can be computed by finding the determinant of a 2xn matrix. For details on how to compute the area, please see the following link: http://mathworld.wolfram.com/PolygonArea.html

Task 4 Sorting
void bubbleSort(int arr[], int n); This function takes in an array of length n, and then sorts it in ascending order. After this function is called, the array passed to this function should be a sorted array. You should implement the sorting algorithm known as bubble sort.

Task 5 Statistics

In this task, you will be implementing some basic functions that are commonly used in statistics and data modeling. float mean(float arr[], int n); This function takes as input an array of length n, and returns the mean value of all the elements contained in that array. For those who do not know how to compute the mean of a given set of numbers, please go back to secondary school. float stdev(float arr[], int n); This function takes as input an array of length n, and returns the standard deviation of all the values contained in that array. For those who do not know how to compute standard deviation, please see the following link: http://www.mathsisfun.com/data/standard-deviation.html float pctile(float arr[], int n, float p); This function takes as input an array of length n, and returns the pth percentile of the entire set. Assume that p is a non-negative number at most 1. The pth percentile is defined as the smallest value which is not greater than p*n numbers in the array. If p*n is not a whole number, then you should use linear interpolation to find the percentile. As an example, assume that the array is the following: 0.2, 1.1, 1.2, 1.7, 2.0, 2.0, 2.1, 2.5, 3.0, 3.2, 3.5, 3.6, 4.0 Although this array is sorted, the array that will be passed to your function might not be, so dont assume that the array is sorted while coding. Assume the value of p is 0.3. The array has 13 elements, so the value of n is 13. p*n = 3.9. However, 3.9 is not a whole number. So we look at the two nearest numbers, i.e.

the third and the fourth numbers, which are 1.2 and 1.7. Then, we can calculate the so- called 3.9th number by using linear interpolation as follows: = 1.2 + 0.9 1.7 1.2 float error(float arrX[], float arrY[], int n, float m, float c); This function should take in a set of n points on the Cartesian plane, whose x coordinates are in arrX, and whose y coordinates are in arrY, and should output the total error obtained when the points are to be approximated by a line with gradient m and y-intercept c. The error is defined as a sum over all points of the squares of the vertical distances of the points from the line. void lsq_fit(float arrX[], float arrY[], int n, float &m, float &c); This function should take as input n points on the Cartesian plane, with x coordinates in the arrX array and y coordinates in the arrY array, and compute the value of m and c, such that the error that is calculated in the previous function is at a minimum. In other words, you are to determine the equation of the regression line of Y on X. Since the values of m and c are passed by reference, you can directly store the computed values in those variables. To learn more about how to calculate regression, please see the following link: http://stattrek.com/ap-statistics-1/regression.aspx

Task 6 Matrix Arithmetic 1


Before we move onto this next task, which involves matrices, we need to see how we can encode and perform operations on matrices. A matrix is simply a 2-dimensional grid of numbers. Now, we can obviously create and use 2D arrays in C++, but were going to go with an alternate format. We will be representing matrices as 1D arrays in C++. This is a much more convenient way to pass matrices around various functions, as you will see later. Assume that youre given the following matrix with m rows and n columns. !! !! = !! !" Then, we can represent this matrix completely using an array in C++ using encoding: !! !" !" !! !" !! !! !" The array would have length mn. The first n elements would be the matrixs first row. The second n elements would be the second row, the third n elements would be the fourth row, and so on. Given such an array, and the values of m and n, how do we determine the value present in the corresponding matrix at row i and column j? Think long and hard about this question and only proceed beyond this point once you have the answer. The following functions will assume that your matrices are encoded into C++ arrays according to the scheme above. void matrixTranspose(float mat[], int n); This function takes in an array representing a matrix, and then transposes it. The matrix is a square matrix, with n rows and n columns. For those who do not know what the transpose is, it is simply the original matrix flipped about the leading diagonal, which means that an element previously at row i and column j will swap positions with the element at row j and column i. void matrixMulSquare(float res[], float mat1[], float mat2[], int n); This function takes in two square matrices, each with n rows and n columns, and then stores the result of mat1 x mat2 in the array res, which is the first argument in the

function. For those who do not know the basics of matrix multiplication, please see the following link: http://en.wikipedia.org/wiki/Matrix_multiplication void transform(float mat[], float vec[], int n); This function should take in a square matrix with n rows and n columns, represented as an array of length n*n, and an n-dimensional vector, represented by an array of length n. The function should compute the result mat x vec, and then store the result in vec itself, i.e. the vector represented by vec should be transformed by the matrix mat. void matrixMul(float res[], float mat1[], float mat2[], int m, int n, int p); This function should take in a matrix mat1 with m rows and n columns, and a matrix mat2 with n rows and p columns, and should multiply the two. The result should be stored in res, which is an array that represents a matrix with m rows and p columns.

Task 7 Simple Games


There are two games you will be implementing in this task, which are essentially variants of each other. This game is played on a square board, and each square has a switch on it. Initially, all the switches are turned off. The player is given a stamp, and then he starts stamping on the board. Every square the stamp touches has its state toggled. If it was off before, it will become on, and if it was on before, it will become off. The stamp might have an irregular shape, which will affect which stamps will be turned on and which will be turned off. The two functions below have identical arguments. The arr is a boolean array that has length nxn. This represents the game board in the same way a matrix is represented as a 1D array. The turnR and turnC are int arrays that represent the row and column locations at which the player stamped at every turn. void IGame(bool arr[], int turnR[], int turnC[], int n); In this function, you will simulate a game in which the user plays with an I-shaped stamp that looks something like this: So, if you were to stamp at row 3 and column 5, then the center of the stamp would be placed on that location, and all of the following squares would be toggled: (3,5) (2,5) (2,4) (2,6) (4,5) (4,4) (4,6) Of course, if some parts of the stamp were to go off the board, then the number of squares toggled might be less, since the stamp wont be entirely touching the board. For example, if you were to stamp at row 1 and column 1, the following squares would be toggled: (1,1) (2,1) (2,2) void KGame(bool arr[], int turnR[], int turnC[], int n); This game is identical to the last one, except that the shape of the stamp is different. The stamp you will play with in this game is K-shaped, like so:

Task 8 Matrix Arithmetic 2 (Hackers Edition)


float matrixDet(float mat[], int n); This function takes in as input an array that represents an nxn square matrix, and computes and returns the determinant of that matrix. To calculate the determinant of a matrix, please see the following link: http://people.richland.edu/james/lecture/m116/matrices/determinant.html void matrixInv(float mat[], int n); This function takes in as input an array that represents a nxn square matrix, and then inverts it. The array itself is modified, so that it becomes the inverse of what it was before.

Task 9 Searching (Hackers Edition)

int unique(int arr[], int n) This function takes in an array that has length 2n-1. The array contains every number in pairs, i.e. every number in the array occurs exactly twice, except one number. This function searches the array for this number that is unique in the array, and then returns that number. However, you may not create any new arrays in this function, only single variables.