First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

Similar documents
University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Second Examination Solution

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

CS 216 Exam 1 Fall SOLUTION

Dynamic Data Structures

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Largest Online Community of VU Students

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

Data Structure (CS301)

CS 2150 Exam 1, Spring 2018 Page 1 of 6 UVa userid:

Part I: Short Answer (12 questions, 65 points total)

UNIVERSITY REGULATIONS

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

ComS 228 Exam 1. September 27, 2004

Midterm Exam. Sample Solutions

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

This examination has 11 pages. Check that you have a complete paper.

Data Structures (CS301) LAB

ECE 250 Data Structures and Algorithms MID-TERM EXAMINATION /5:30-7:00

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

1 Short Answer (10 Points Each)

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

! Mon, May 5, 2:00PM to 4:30PM. ! Closed book, closed notes, clean desk. ! Comprehensive (covers entire course) ! 30% of your final grade

You must include this cover sheet. Either type up the assignment using theory3.tex, or print out this PDF.

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

Chapter 1: Object-Oriented Programming Using C++

Review Questions for Final Exam

CS24 Week 4 Lecture 2

Example Final Questions Instructions

Prelim 1. CS2110, October 2, 2014, 5:30 PM Extra Total Question TrueFalse Multiple Object Oriented

! A data type for which: ! An ADT may be implemented using various. ! Examples:

Data Structures and Algorithms Winter Semester

Introducing C++ to Java Programmers

CS 162, Lecture 25: Exam II Review. 30 May 2018

ECE 250 Data Structures and Algorithms MID-TERM EXAMINATION B /13:30-14:50 MC-4021/RCH-211

CSCE 2014 Final Exam Spring Version A

CS 455 Final Exam Spring 2015 [Bono] May 13, 2015

Multiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:30-7:00

CS 61B, Spring 1996 Midterm #1 Professor M. Clancy

CS 2604 Homework 1 C++ Review Summer I 2003

CS 455 Final Exam Spring 2017 [Bono] May 10, 2017

CS350 - Exam 1 (100 Points)

THE UNIVERSITY OF WESTERN AUSTRALIA

CSE143 Exam with answers Problem numbering may differ from the test as given. Midterm #2 February 16, 2001

1 Short Answer (7 Points Each)

Introduction to the C programming language

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam.

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Introduction to the C programming language

UNIVERSITY REGULATIONS

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

: Principles of Imperative Computation, Spring Homework 3 Theory [Update 1]

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

CS2255 HOMEWORK #1 Fall 2012

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS 314 Exam 2 Spring

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

Summer Final Exam Review Session August 5, 2009

Spring 2008 Data Structures (CS301) LAB

CS24 Week 3 Lecture 1

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Arrays and Linked Lists

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

Instantiation of Template class

FORM 2 (Please put your name and form # on the scantron!!!!)

Midterm Exam (REGULAR SECTION)

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

CS171 Midterm Exam. October 29, Name:

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

Largest Online Community of VU Students

Linked List using a Sentinel

CSE 303: Concepts and Tools for Software Development

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Transcription:

Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2008 7p-9p, Tuesday, February 19 Name: NetID: Lab Section (Day/Time): This is a closed book and closed notes exam. No electronic aids are allowed, either. You should have 5 problems total on 17 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 implementation 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. Please put your name at the top of each page. Problem Points Score Grader 1 20 2 20 3 20 4 20 5 20 Total 100

1. [Pointers, Parameters, and Miscellany 20 points]. MC1 (2.5pts) Which of the following is a correct way to declare an instance of a stack whose parameterized type is an integer? (a) stack s int ; (b) stack int s; (c) stack s(int); (d) more than one of (a), (b), and (c) are correct. (e) none of the above is correct. MC2 (2.5pts) Consider the following C++ statements: #include <iostream> using namespace std; void increment1(int x) { x++; void increment2(int* x) { x++; void increment3(int& x) { x++; int main() { int x = 1; increment1(x); increment2(&x); increment3(x); cout << x << endl; return 0; What is the printed out when this code is compiled and run? (a) 1 (b) 2 (c) 3 (d) 4 (e) none of the above

MC3 (2.5pts) Consider the following lines of C++: int* x, y; int z = 10; x = &z; y = x; *x = 15; cout << z is << z << endl; What is their result? (a) Print z is 10 to standard out. (b) Print z is 15 to standard out. (c) The code will not compile due to a type error. (d) The code will compile but it will segfault. (e) None of these options describes the behavior of this code. MC4 (2.5pts) Given an array-based implementation of a list of n elements, what is the worst case running time for inserting an element to an arbitrary position in the list? (a) O(1) (b) O(log n) (c) O(n) (d) O(n 2 ) (e) None of the above

MC5 (2.5 pts) Consider the following partial function definition: sphere bounce(sphere & s) { sphere t(s); // play with s and t (no copy constructors happen here) return t; How many times is the copy constructor employed when the bounce function is executed? (a) 0 (b) 1 (c) 2 (d) 3 (e) There is no way to tell how many times the copy constructor is called. MC6 (2.5pts) Suppose myvar is declared as follows: int ** myvar;. Which of the following could describe the variable myvar once it has been initialized? I. myvar is a dynamic array of integer pointers. II. myvar is a pointer to a dynamic array of integers. III. myvar is a dynamic array of dynamic arrays of integers. (a) None are a valid description of myvar. (b) Only I. is a valid description of myvar. (c) I. and III. are valid descriptions of myvar. (d) I. and II. are valid descriptions of myvar. (e) All three are valid descriptions of myvar.

MC7 (2.5pts) Consider the following partial class definitions: class Sphere { private: double theradius; public: // Lots of member functions go here. virtual double getarea() const; // ***computes surface area*** virtual void displayarea() const; // displayarea() includes the statement "cout << getarea() << endl;" ; class Ball: public Sphere { private: string thename; public: // Lots of member functions. Note: Ball class inherits displayarea(). double getarea() const; // ***computes cross sectional area*** ; Now suppose you have the following in your main() function: Sphere mysphere; Ball myball; myball.displayarea(); Which of the following describes the behavior of this code in main()? (a) myball s surface area is displayed. (b) myball s cross sectional area is displayed. (c) The call to getarea() within displayarea() is ambiguous, so there is a compile error. (d) A bus error occurs at run time. (e) None of these options describes the behavior of this code. MC8 (2.5pts) Which of the following characterize C++ as an object oriented programming language? (a) Pointers, memory management, and inheritance. (b) Polymorphism, memory management, and encapsulation. (c) Polymorphism, inheritance, and encapsulation. (d) Pointers, inheritance, and overloading operators. (e) Overloading operators, inheritance and encapsulation.

2. [The Big Three 20 points]. Consider the following partial class definition: class CollegeCourse { private: Image** studentphotos; int* studentids; std::string* professor; int maxclasssize; int courseid; // some helper functions public: // constructors and destructor CollegeCourse(const CollegeCourse & source); ; // lots of public member functions The studentphotos structure is a dynamically allocated array of Image pointers. studentids structure is a dynamically allocated array of ints. Both studentids and studentphotos arrays have maxclasssize elements. You can assume that maxclasssize is greater than zero. professor is a dynamically allocated string object. The In this question you will write the copy constructor for the CollegeCourse class that you would include in the collegecourse.cpp file. You may assume that all pointers are valid. That is, they are either NULL or they point to an object of the specified type. Furthermore, you may assume that the Image and string classes have an appropriately defined Big Three (destructor, copy constructor, and assignment operator). You may write your answer on the following page. To grade this problem, we will first read your comments to make sure you intend to do the right thing, and then we ll check your code to make sure it does what your comments say it should. As a result, be sure your comments are coherent, useful, and reflective of your approach to the problem.

Solution: CollegeCourse(const CollegeCourse & source) { maxclasssize = source.maxclasssize; courseid = source.courseid; // allocate new memory for studentphotos and studentids studentphotos = new Image*[maxClassSize]; studentids = new int[maxclasssize]; // make a deep copy of professor using string copy constructor if(source.professor!= NULL) { // not required but is better to check professor = new string(*source.professor); else { professor = NULL; for(int i = 0; i < maxclasssize; ++i) { // check for NULL pointer to avoid segfault if(source.studentphotos[i]!= NULL) { // make a deep copy of studentphotos using Image copy constructor studentphotos[i] = new Image(*source.studentPhotos[i]); // source Image pointer is NULL, so set the copy s pointer to NULL else { studentphotos[i] = NULL; // make a deep copy of studentids studentids[i] = source.studentids[i]; Grading Rubric (20pts) 1pt - copy maxclasssize 1pt - copy courseid 2pts - dynamically allocate new memory for studentphotos 1pt - dynamically allocate new memory for studentids 2pts - deep copy of professor 2pts - check for NULL before dereferencing source.professor 2pts - deep copy of studentphotots 1pt - set studentphotos[i] to NULL if source.studentphotos[i] is NULL 2pts - deep copy of studentids 2pts - comment about memory allocation 1pt - comments about NULL handling

3pts - comments about deep copying studentids, studentphotos, and professor Penalties: -1 pt for a syntax error -1 pt setting a local CollegeCourse instance rather than the instance variables -1 pt redeclaring instance variables as local variables -1 pt for self assignment checking -1 pt for returning anything from constructor -2 pts for deallocating invalid pointers in a copy constructor

3. [Short answer 20 points]. (a) (5 points) One problem with an array-based implementation of a stack is the resizing we must do when the stack fills. A scheme for overcoming this drawback employs periodic resizing of the array by some constant amount c. That is, when the array of size k fills, we create a new array of size k + c and copy the elements from the original array into the new one, maintaining the original order so that the stack is not corrupted. Give a complete analysis of this scheme over a sequence of n push operations on the stack. Assume that the stack is empty to start. Please report your answer as an average cost per push. Solution: over n pushes there are n/c copying events, and that in the ith copy event, i c data items are copied from the old full array to the new one. The following sum reflects the total number of copies: n n c c i c = c i = c 2 n c (n c + 1) = O(n2 ) i=0 i=0 Over n pushes the average cost per push is thus O(n). Rubric: 3 points for analysis, 2 points for correct answer. Two of three analysis points were awarded for any answer in which the process was decomposed appropriately into the number of copy events and the size of each, even if the values used were incorrect. Forgetting to report the average was a 1 point penalty. (b) (5 points) Suppose a queue is implemented as a singly-linked list with head and tail pointers, and the back of the queue is at the head of the list (that is, enqueues occur at the head of the list). What is the worst case running time of the best implementation of a dequeue() operation? Solution: in order to complete the dequeue operation and end with a tail pointer at the last element in the list, we must first traverse the list to find the node BEFORE the one we wish to delete. This is a linear time operation in the number of nodes in the list, or O(n). Rubric: 3 points for analysis, 2 points for correct answer. Any answer that assumed the tail pointer could be moved back without traversing the list received a maximum of 2 points. (c) (5 points) Suppose a queue is implemented as a singly-linked list with head and tail pointers, and the back of the queue is at the head of the list (as in the previous part of the question). We want to implement a clearqueue() function that removes all the data from the queue. What is the worst case running time of the best implementation of a clearqueue() operation? Solution: we can simply traverse the list, deleting elements as we go, for a total running time of O(n), where n is the number of elements in the list. Rubric: 3 points for analysis, 2 for correct answer. Note that an incorrect answer to part 2 could result in a correct answer for this problem. Such responses received only the 2 points for the correct answer, and no analysis points. Answers that called dequeue repeatedly received 3 points if the analysis was correct.

(d) (5 points) Consider the following template function definition: template <class T, class U> T addem(t a, U b) { return a + b; Describe what happens in each of the following calls to addem. i. addem<int,int>(3,4); Solution: returns integer 7. ii. addem<double,int>(3.2,4); Solution: returns double 7.2. iii. addem<int,double>(3,4.5); Solution: returns integer 7. iv. addem<string,int>("hi",4); Solution: This is a compiler error unless the + sign is overloaded to add integers to strings. v. addem<string,string>("bye","hi"); Solution: returns string byehi. Rubric: one point each part.

4. [Lists: Orders of Magnitude 20 points]. You are given the following ListNode class: class ListNode { public: int element; ListNode* next; ; and a singly-linked list made up of such nodes, with a head pointer but no tail pointer. We will further guarantee that all the integers stored in the nodes are nonnegative. You should write a function that reorders the list so that it is sorted by order of magnitude. That is, all the 1-digit numbers would appear first, followed by all the 2-digit numbers, and so on. Within a given order of magnitude, the list elements should appear in their original order. As an example, the input list 35->2->44->420->56789->65->287->8->48->NULL should end up looking like 2->8->35->44->65->48->420->287->56789->NULL. Your function should also print out how many elements of each order of magnitude are in the list. The function should be named OrderMagnitude, return nothing, and have one parameter, a reference to a ListNode pointer, which will point to the head node of a singlylinked list. You may not create or delete any ListNodes in writing this function, but you can declare as many additional ListNode pointers as you need. (Hint: You may find it useful to know that the largest number an int can hold is 2147483647.) You may write your answer on the following page. To grade this problem, we will first read your comments to make sure you intend to do the right thing, and then we ll check your code to make sure it does what your comments say it should. As a result, be sure your comments are coherent, useful, and reflective of your approach to the problem. Finally, your score on this problem will be based on both the accuracy and the efficiency of your approach.

Solution: void OrderMagnitude(ListNode*& list_head) { if (list_head == NULL) return; // declarations and initializations ListNode* temp = list_head; // == head, by assumption ListNode *newheads[10], *newtails[10], *tail; int counts[10], order; for (int i=0; i<10; i++) { newheads[i] = NULL; newtails[i] = NULL; counts[i] = 0; // determine order of the element -- we know temp->element >= 0 while (temp!= NULL) { if ( temp->element < 10) // order 10^0 order = 0; elseif ( temp->element < 100) // order 10^1 order = 1; elseif ( temp->element < 1000) order = 2; elseif ( temp->element < 10000) // if the math library order = 3; // is included, this can elseif ( temp->element < 100000) // be reduced to order = 4; // order = log10(temp->element); elseif ( temp->element < 1000000) // which implicitly converts order = 5; // the double given by log10 elseif ( temp->element < 10000000) // to an int for us order = 6; elseif ( temp->element < 100000000) order = 7; elseif ( temp->element < 1000000000) order = 8; else // order 10^9 order = 9; // put it in the correct sublist counts[order]++; if (newheads[order] == NULL) // first element of this magnitude newheads[order] = newtails[order] = temp; else { // add it to the sublist, and update the tail newtails[order]->next = temp; newtails[order] = temp;

temp = temp->next; // now all the nodes are in their correct sublists // link up all the sublists int i = 0; while (counts[i] == 0) i++; // increment until the first sublist with nodes is found list_head = newheads[i]; // set head for complete list tail = newtails[i]; // set tail of new list so far for (int j=i+1; j<10; j++) { if (newheads[j]!= NULL) { // if anything is in this sublist tail->next = newheads[j]; // link it up tail = newtails[j]; // move tail to new tail tail->next = NULL; // set end of completed list // print out orders cout << "The numbers in the list are distributed as follows:" << endl; for (int i=0; i<10; i++) { cout << i+1 << "-digit numbers in the list: " << counts[i] << endl; // end function Grading scheme: 5 points for comments 11 points for correct code: 2 pts - declare and initialize appropriate variables 1 pt - determine the order of each element 1 pt - keep track of number of each order 2 pts - move element into the correct sublist 3 pts - correctly link the sublists 2 pts - print out the number of elements of each order 4 points for efficiency: +4 pts if O(n) with one pass through the list +2 pts if other O(n) solution (usually 10 passes through the list) +1 pt for anthing else that works (e.g., O(n 2 ) running time) Miscellaneous deductions: -12 pts if the whole list was sorted instead of following the problem spec -2 pts if elements in an order of magnitude appear in a different order in the final list

-1 pt for misuse of a library function -1/2 pt each for syntax errors (up to -4 pts) -2 pts if any ListNodes were created or deleted -2 pts if helper functions were declared or used

5. [Queues and Stacks 20 points]. (a) Imagine that you are given a standard Stack class and Queue class, both of which are designed to contain integer data (interface provided on following pages). Your task is to write a function called scramble that takes one argument: a reference to a Queue. The function should reverse the order of SOME of the elements in the queue, and maintain the order of others according to the following pattern: The first element stays on the front of the queue. Then the next two elements are reversed. Then the next three elements are placed on the queue in their original order. Then the next four elements are reversed. Then the next five elements are place on the queue in their original order. etc. For example, given the following queue, front rear 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 we get the following result: front rear 00 02 01 03 04 05 09 08 07 06 10 11 12 13 14 16 15 Any leftover numbers should be handled as if their block was complete. See for example the way 15 and 16 were treated in our example above. We are putting some constraints on your implementation. Specifically, you must write the function using only the variable declarations we provide. We are allowing you four local variables: two ints, one Stack, and one Queue. You may write your answer on the following page. To grade this problem, we will first read your comments to make sure you intend to do the right thing, and then we ll check your code to make sure it does what your comments say it should. As a result, be sure your comments are coherent, useful, and reflective of your approach to the problem.

problem 5 continued... Solution: void scramble(queue & queue) { int temp1, temp2; // These names are generic to avoid Stack s; // giving you too many clues about Queue q; // how we think you should use them. temp1=0; //keeps track of current block size while(!queue.isempty()) { temp1++; //increment block size if(temp1%2) //odd block size //move next block from queue to q for(temp2=0;temp2<temp1;temp2++) if(!queue.isempty()) q.enqueue(queue.dequeue()); else //even block size { //move next block from queue to s for(temp2=0;temp2<temp1;temp2++) if(!queue.isempty()) s.push(queue.dequeue()); //move s to q, reversing elements while(!s.isempty()) q.enqueue(s.pop()); //move back into the original queue while(!q.isempty()) queue.enqueue(q.dequeue()); Grading Rubric (15pts) up to 5 pts - comments up to 5 pts - concept/logic up to 5 pts - c++ Penalties: -1 pt for each small problem, i.e. -1 pt for pop or dequeue on an empty stack or queue -1 pt for defining extra variables -1 pt for invalid return

(b) (5 points) Analyze the running time of the code you wrote in part (a). You should state the worst-case time complexity of your code when operating on a list with n nodes and briefly explain why it would take that much time. Solution: Each push, pop, enqueue, and dequeue takes O(1) time. Elements in odd blocks each force a dequeue from queue, an enqueue to q, a dequeue from q, and an enqueue to queue. Elements in even blocks each force a dequeue from queue, a push to p, a pop from p, an enqueue to q, a dequeue from q, and an enqueue to queue. Thus for each element originally in queue a constant number of operations are performed so scramble runs in O(n) time. Grading Rubric (5 pts) 3 pts for correct answer 2 pts for analysis

class Stack { // partial class definition public: Stack(); void push(int e); int pop(); bool isempty(); // returns true if the stack is empty ; private: // we re not telling class Queue { // partial class definition public: Queue(); ; void enqueue(int e); int dequeue(); bool isempty(); // returns true if the queue is empty private: // we re not telling

(scratch paper, page 1)

(scratch paper, page 2)