|
CSci 152: Computer Programming II |
|
Fall 2004 |


|
Programming Assignment #3 |
|
The solution given here shows an example of how one might go about writing a C++ program that satisfies all of the requirements of assignment #3 and runs correctly In this solution I use a struct in order to simplify passing around sets to functions. The SetType struct has 2 members, simply the number of elements in the set (size) and an integer array that holds the elements themselves. The main function is responsible for opening the file, then reading in pairs of lines and treating them as sets. I use a function to read a set from standard input (readSet). This function takes an input stream as a parameter, read in a line of data from that stream, populates a newly created SetType with the data, and returns the new SetType as the result. I read a line by one of the methods that we spoke of in class, where I try and peek ahead to see if I’ve gotten to the end of the line yet or not, if not I go ahead and assume the element we are reading is an int, and read it in.
After reading in a set, the loop in main calls several functions to process the set. We display the set (displaySet), sort the set (sort) and remove duplicates from the set (removeDuplicates). The sort and removeDuplicates receive the SetType as a reference parameter, so that the results of sorting the set then removing the duplicates are passed back to the caller. The sort is a copy of Malik’s sorting function using the selection sort, modified slightly to accept a SetType parameter rather than an array and size parameters separately. The reading in, displaying, sorting and removal of duplicates is done twice, once for input set A and once for input set B. This shows the power of using functions as we can reuse all of the code to do the exact same thing for the 2 sets to be manipulated.
Once sets A and B are properly read in I call functions that perform the union on the sets (setUnion) the intersection (setIntersection) and the difference (setDifference). Each of these functions takes 2 sets as parameters and returns a new resulting set. All 3 of these functions work in a similar way. They assume the input sets are already sorted and have no duplicates. They then iterate through both sets A and B, keeping a separate index into each sets array. Sets.cpp – An example solution for Assignment #3. We read in 2 sets from a file (sorting them and removing duplicates) then perform intersection, union and difference operations on the sets. |
|
Programming Assignment #2 example solution |
Example Solution |
