Exam 1 Solved - Data Structures - Spring 2012 | CS 225, Exams of Data Structures and Algorithms

Material Type: Exam; Professor: Heeren; Class: Data Structures; Subject: Computer Science; University: University of Illinois - Urbana-Champaign;

Typology: Exams

2011/2012

Uploaded on 03/09/2012

ryan9986
ryan9986 🇺🇸

2 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
University of Illinois at Urbana-Champaign
Department of Computer Science
First Examination RUBRIC
CS 225 Data Structures and Software Principles
Spring 2012
7-9p, Tuesday, February 21
Name:
NetID:
Lab Section (Day/Time):
Labs this week are officially cancelled. We are loading up the calendar with lab hours,
so if you are still working on MP3 you will be able to find course staff to help you.
This is a closed book and closed notes exam. No electronic aids are allowed, either.
You should have 5 problems total on 20 pages. The last two sheets are scratch paper; you
may detach them while taking the exam, but must turn them in with the exam when you
leave.
Unless otherwise stated in a problem, assume the best possible design of a particular imple-
mentation is being used.
Unless the problem specifically says otherwise, (1) assume the code compiles, and thus any
compiler error is an exam typo (though hopefully there are not any typos), and (2) assume
you are NOT allowed to write any helper methods to help solve the problem, nor are you
allowed to use additional arrays, lists, or other collection data structures unless we have said
you can.
We will be grading your code by first reading your comments to see if your plan is good,
and then reading the code to make sure it does exactly what the comments promise. In
general, complete and accurate comments will be worth approximately 30% of the points on
any coding problem.
Please put your name at the top of each page.
Problem Points Score Grader
1 20
2 20
3 24
4 17
5 19
Total 100
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Exam 1 Solved - Data Structures - Spring 2012 | CS 225 and more Exams Data Structures and Algorithms in PDF only on Docsity!

University of Illinois at Urbana-Champaign

Department of Computer Science

First Examination RUBRIC

CS 225 Data Structures and Software Principles

Spring 2012

7-9p, Tuesday, February 21

Name: NetID: Lab Section (Day/Time):

  • Labs this week are officially cancelled. We are loading up the calendar with lab hours, so if you are still working on MP3 you will be able to find course staff to help you.
  • This is a closed book and closed notes exam. No electronic aids are allowed, either.
  • You should have 5 problems total on 20 pages. The last two sheets are scratch paper; you may detach them while taking the exam, but must turn them in with the exam when you leave.
  • Unless otherwise stated in a problem, assume the best possible design of a particular imple- mentation is being used.
  • Unless the problem specifically says otherwise, (1) assume the code compiles, and thus any compiler error is an exam typo (though hopefully there are not any typos), and (2) assume you are NOT allowed to write any helper methods to help solve the problem, nor are you allowed to use additional arrays, lists, or other collection data structures unless we have said you can.
  • We will be grading your code by first reading your comments to see if your plan is good, and then reading the code to make sure it does exactly what the comments promise. In general, complete and accurate comments will be worth approximately 30% of the points on any coding problem.
  • Please put your name at the top of each page.

Problem Points Score Grader 1 20 2 20 3 24 4 17 5 19 Total 100

  1. [Pointers, Parameters, and Miscellany – 20 points].

MC1 (2.5pts)

Consider the following statements, and assume the standard iostream library has been in- cluded:

int s; int * t; s = 8; *t = s; cout << *t << endl;

What is the result of executing these statements? (a) 8 is sent to standard out. (b) The memory address of w is sent to standard out. (c) This code does not compile. (d) This code results in a runtime error. (e) None of these options is correct.

MC2 (2.5pts)

What is the output of the following sequence of C++ statements? (The sphere class interface is included at end of the exam.)

sphere * a, * b;

a = new sphere(1.0); b = a; b->setRadius(2.0); delete b;

a->setRadius(4.0); sphere * c = new sphere(5.0); b = new sphere(3.0);

cout << a->getRadius() << endl;

(a) 3. (b) 4. (c) An unpredictable runtime memory error. (d) A compiler error on line a->setRadius(4.0);. (e) None of these is the correct choice.

MC5 (2.5pts)

Consider the following statements, and assume the standard iostream library has been in- cluded:

void funwon(int x) { x = 1;} void funtoo(int * x) { *x = *x + 2; } void funfor(int & x) { x = x + 4; }

int main() {

int x = 0;

funwon(x); funtoo(&x); funfor(x);

cout << x << endl;

return 0; }

What is the result of executing these statements?

(a) 4 is sent to standard out. (b) 5 is sent to standard out. (c) 6 is sent to standard out. (d) This code does not compile because of a type mismatch in funfor. (e) None of these options is correct.

MC6 (2.5pts)

Consider the following code, and assume the standard iostream and list class have been included.

template < class Iter, class Formatter > bool mystery(Iter first, Iter second, Formatter runit) { bool p = true; while (first != second) { p = (p && runit(*first, *second)); first++; second--; } return p; }

class noClue { public: bool operator()(int a, int b) { return (a==b); } };

int main() {

list s;

// some number of insertions to s here

list::iterator it1 = s.begin(); list::iterator it2 = s.end(); it2--;

noClue dunno; if ( mystery<list::iterator, noClue>(it1, it2, dunno)) cout << "yes" << endl; else cout << "no" << endl;

return 0; }

  1. [MP2ish – 20 points]. Consider the following partial class definition:

class Book{ private: string * text; int length; public: Book(const char * fileName); // places each word from a file into // sequential locations in the text array. // Sets length to be the number of words in the text. ~Book(); // Member functions that allow access to the contents of the text array. // Declaration of the operator== function for this problem. }

class Library { private: Book ** shelf; int shelfSize;

// some helper functions

public: // constructors and destructor Library(int num); // constructor for a Library with space for num books

// operator= declaration

// lots of other public member functions not relevant to this problem };

A Book is implemented as a dynamically allocated array of strings in a variable called text. The Book constructor simply opens a given text file and places each word and punctuation mark into sequential positions in the text array. (White space is discarded upon reading the input file.)

A Library is implemented as a collection of books. The shelf structure is a dynamically allocated array whose entries are Book pointers. The array shelf has shelfSize elements. A pointer to a Book is added to the shelf structure in the cell whose index corresponds to the location of the book in the Library. Any position in the Library can be empty (NULL) or not (containing a valid pointer to a Book.

You can assume the string class has been included and scoped, and that Books always contain at least one word.

You may assume that all pointers are valid. That is, they are either NULL or they point to an object of the specified type. In particular, the Library(int num) constructor builds a dynamic array of length num, whose elements are all NULL, and sets shelfSize to num.

In this question you will help us implement some of the member functions for the Library and Book classes.

You will write your answers on the following pages. Adding comments to our code skeletons can get you partial credit, but it’s not required.

(a) (10 points) In this part of the problem, you will write the code for an overloaded boolean comparison operator, operator==() so that two Books can be compared. Two Books are the same if their text arrays contain identical strings in each position. We have given you a skeleton for your code. If you need to add a couple lines, just do it neatly between our lines. If your approach is significantly different than ours, please write your response on the back of the previous page.

bool Book::_operator==(const Book & rhs) // 2 points {

bool returnValue = true; // 2 points

if (length == rhs.length) // 1 point

for(int i = 0; i < length ; i++) // 1 point {

__if (text[i] != rhs.text[i]) __ // 2 points

______returnValue = false;__ // 1 point }

else returnValue = false_; // 1 point

return returnValue; }

  1. [MP3ish – 24 points].

The following code is a partial definition of a doubly linked list implementation of the List class that you used for MP3. Note in particular that it does not contain sentinels, but it does have head and tail pointers.

template class List { public: // ~List() -- Destructor // Frees all memory associated with the current list. ~List();

// insertFront() -- Inserts a new node at the front of the list. void insertFront(const T & ndata);

// insertBack() -- Inserts a new node at the back of the list. void insertBack(const T & ndata);

// a bunch of other List class functions

private:

class ListNode { public: // ListNode constructor // - initializes element to default Etype, and pointers to NULL ListNode();

// ListNode constructor // - parameters : value - the value to store in the element field // - initializes node to hold value and NULL pointers ListNode(T const & value);

ListNode* next; // pointer to next node in list ListNode* prev; // pointer to prior node in list T element; // holds element of node };

ListNode* head; // points to first node of list ListNode* tail; // points to last node of list ListNode* curr; // an extra pointer for your convenience int size; };

(a) (4 points) Please implement the List class destructor (as you did for MP3). This function simply frees all memory associated with the current list object. You may use the private member curr, if you would like. We will make no assumptions about its value after a call to the destructor.

Be sure to make your code very neat and easy to read. Draw pictures where it will help us, and comment profusely. Solution:

template List::~List() { while(head != NULL) { curr = head; head = head->next; delete curr; } }

Grading: 1pt for signature (first two lines) 2pt for the general case (must have some sort of loop) 1pt for handling edge cases (when head == tail or head == NULL) -1pt for 1+ major or 2+ minor syntax errors

(b) (4 points) Describe two instances when the system invokes the List class destructor.

Rubric: each part is worth 2 points.

  • The classname destructor is called when an object of type classname goes out of scope.
  • The classname destructor is called when a pointer to an object of type classname is deleted.

//set rightside of ’left’ left->next=tmpRight; tmpRight->prev=left;

//set rightside of ’right’ if(tmpLeft!=right) { right->next=tmpLeft; tmpLeft->prev=right; } else right->next=left;

Grading Rubric: 2pts: Adequate commenting. 1pts: Any reasonable attempt to swap left and right assuming nodes in the middle. 1pts: Considering the case that there are no nodes between left and right 4pts: For the pointers

(d) (8 points) On each line below, tell the worst case running time of the best algorithm for each function and implementation described. Rubric: each part is worth 2 points.

i. O(1) State the running time for function insertRear for the List class given in this problem.

ii. O(1) State the running time for function insertRear for a List implemented using a singly linked list with a tail pointer but no tail sentinel.

iii. O(1) State the running time for function removeRear for a List implemented using a dynamic array.

iv. O(n) State the running time for function removeRear for a List implemented using a singly linked list with a tail pointer but no tail sentinel.

  1. [MaxList – 17 points].

In this problem we will be investigating a variation of a linked list that we will call a MaxList. As illustrated in the figure below, this list has a head pointer and a head sentinel. In addition, each MaxListNode has non-negative integer data, a next pointer, and a maxPrev pointer that points to the maximum valued node before and including the current node. Look carefully at the picture to make sure you understand the structure.

0

head

5 2 4 7

(a) (2 points) In this diagram, we have just invoked the function call insertAt(3,8) which places the value 8 in the third position in the list. Draw the accurate maxPrev pointers, notice which ones may change (depending on the value inserted), and which ones will certainly not change.

0

head

5 2 8 4 7

(b) (2 points) In this diagram, we have just invoked the function call insertAt(3,3) which now places the value 3 in the third position in the list. Draw the accurate maxPrev pointers. In this example, you should pay particularly close attention to how the maxPrev pointer is set for the new node.

0

head

5 2 3 8 4 7

The following code is a partial definition of the MaxList class. (Continued on next page.)

class MaxList { public: MaxList(); // YOU’LL DEFINE

// the big 3: (given) copy ctor, dtor, and op= int size() const; // (given) the number of data elts in list

length = 0; MaxListNode *temp = new MaxListNode(0); //1 point temp->next = NULL; temp->maxPrev = temp; //1 point head = temp; //1 point }

(d) (5 points) Implement the public insertAt function so that it behaves as described in parts (a) and (b) of this problem. For simplicity, you may assume that the list is always long enough to accept a new value in position k. As illustrated above, the first data (non-sentinel) element occupies position 1, the second occupies position 2, etc. You may use any of the private member functions you would like. void MaxList::insertAt(int k, int ndata){

MaxListNode * ptr = find(k-1,head); // (1 pt for variable, 1 pt for function) insterAfter (ptr,ndata); // (1pt) fixPtrsAfter(ptr); // (1pt) length++; // (1pt) // Note: Max of 3 points for not using helper functions

} (e) (2 points) Imagine an implementation of a function called insertAtFront that adds a new value to the front of the list. What is the running time of such a function in the worst case? (Circle the appropriate answer.)

constant time (O(1)) linear time (O(n))

(f) (3 points) Briefly explain why the find function is in the private: section of the class definition. Solution: The function returns a MaxListNode * which is a class defined within the private section of the MaxList class. Since client code does not have access to the MaxListNode type, it doesn’t make sense to make find available to them. Furthermore, MaxListNode SHOULD be private because making it public would disclose implemen- tation details that are not relevant to client code.

  1. [Miscellaneous – 19 points].

(a) (6 points) For this problem, you will be a code critic. Please answer the questions below about the following sphere class member function. setPictureGetRadius is supposed to change the member variable thePicture and return the current value of member variable theRadius. The adapted sphere class appears at the end of the exam.

double sphere::setPictureGetRadius(PNG & newPicture) const {

thePicture = newPicture; return theRadius;

} i. (2 points) Comment on the type specification in the parameter list. Is there a better way to specify that parameter? Why is it pass-by-reference? Solution (1 point each valid point): The parameter should be a const reference since it’s an input parameter, and since pass-by-reference allows parameter values to be changed. The parameter is pass-by-reference because pictures are large, and passing by value would take too much time. also, the parameter should be a const reference since newPic should not be changed– it’s just an input parameter. 5aii) what you said, + it’s bad for it to say const there because the whole purpose of the function is to set a private member. 5aiii) actually, it is a reasonable assumption you HAVE to trust that your objects are implemented correctly. and further, if it doesn’t have an op=, then it might also not have a cctor or destructor, which is nuts. i)It is pass-by-refernce as it is faster than pass-by-value. (2 points) ii)’const’ ensures that there will be no changes to the members of the class Sphere. (2 points) iii)The assignment ’thePicture = newPicture’ assumes that the copy constructor has been implemented. No, this is not a reasonable assumption. (2 points)

ii. (2 points) Comment on the const keyword in the function prototype. Solution: The const ensures that there will be no changes to the members of the class Sphere. Since one of the main purposes of the function is to change a private member, the const keyword in that location is ill advised.

iii. (2 points) What does the assignment thePicture = newPicture; assume about the PNG class? Is this a reasonable assumption? Solution: the assignment assumes that the PNG class implements the assignment operator. This is a reasonable assumption, since if it didn’t, the class would be

(c) (4 points) Scrutinize the following code. In this problem we are going to ask you to pre- dict and to change its output. (Please assume that the standard iostream is included.) class yell{ public: void display() { cout << "yell" << endl; } };

class w00t:public yell { public: void display() { cout << "w00t" << endl; } };

int main() {

yell * a = new w00t; a->display();

return 0; } i. (2 points) What is output when the code above is compiled and run? Solution: ”yell” is sent to standard out.

ii. (2 points) How can you change the code so that the other expression is printed without making any changes to the client code? Solution: the display function becomes polymorphic when you use the keyword virtual in the front of the function declaration in the yell class definition.