Docsity

Computer Science Course Material: Templates, Linked Lists, Trees, Graphs, and Class Design, Study notes of Programming Abstractions

Toggle sidebar
bg1
CS106B Handout #36
J Zelenski Mar 10, 2008
Final Practice
Final exam: Friday March 21 12:15-3:15pm
Location TBD (but definitely not Terman )
This is the university-scheduled time for our exam and we are looking forward to seeing all your
smiling faces. If you are one of the few students who approached us at the start of the quarter
about an unavoidable conflict, please follow up with head TA Jason about the alternate exam
Thursday 12:15pm. There will be absolutely no other alternates.
SCPD students: Local SCPD students are asked to attend the regular on-campus exam. This
ensures you will be able to ask questions and receive any clarifications that might come up
during the exam. Folks outside the Bay Area will take the exam at your local site on Friday.
Your SCPD site coordinator will administer the exam. Please send e-mail to Jason
to initiate the arrangements.
Coverage
The final is comprehensive and covers material from the entire quarter, but will tend to focus on
the topics covered after the midterm. This means you should come prepared for nitty-gritty
implementation-side work (pointers, linked lists, trees, graphs, templates, and so on).
It will be a 3-hour exam. It will be open book /open note, but no electronics.
This handout is intended to give you practice solving problems that are comparable to those
which will appear on the exam. These problems were chosen from recent exams as fairly
representative in terms of format, content, and difficulty.
We highly recommend working through the problems in test-like conditions to prepare for the
actual exam. To encourage this, we won't even give out the solutions until next class. Many of
our section problems have been taken from previous exams and chapter exercises from the reader
often make appearances in same or similar forms on exams, so both of those resources are a
valuable source of study material as well.
Be sure to bring the reader with you to the exam. We won't repeat the standard class definitions
on the exam, so the reader appendix will come in handy for looking up the library interfaces.
(FYI: All the space usually left for answers was removed in order to conserve trees).
pf3
pf4
pf5

Partial preview of the text

Download Computer Science Course Material: Templates, Linked Lists, Trees, Graphs, and Class Design and more Study notes Programming Abstractions in PDF only on Docsity!

CS106B Handout # J Zelenski Mar 10, 2008

Final Practice

Final exam: Friday March 21 12:15-3:15pm

Location TBD (but definitely not Terman )

This is the university-scheduled time for our exam and we are looking forward to seeing all your smiling faces. If you are one of the few students who approached us at the start of the quarter about an unavoidable conflict, please follow up with head TA Jason about the alternate exam Thursday 12:15pm. There will be absolutely no other alternates.

SCPD students : Local SCPD students are asked to attend the regular on-campus exam. This ensures you will be able to ask questions and receive any clarifications that might come up during the exam. Folks outside the Bay Area will take the exam at your local site on Friday. Your SCPD site coordinator will administer the exam. Please send e-mail to Jason to initiate the arrangements.

Coverage

The final is comprehensive and covers material from the entire quarter, but will tend to focus on the topics covered after the midterm. This means you should come prepared for nitty-gritty implementation-side work (pointers, linked lists, trees, graphs, templates, and so on).

It will be a 3-hour exam. It will be open book /open note, but no electronics.

This handout is intended to give you practice solving problems that are comparable to those which will appear on the exam. These problems were chosen from recent exams as fairly representative in terms of format, content, and difficulty.

We highly recommend working through the problems in test-like conditions to prepare for the actual exam. To encourage this, we won't even give out the solutions until next class. Many of our section problems have been taken from previous exams and chapter exercises from the reader often make appearances in same or similar forms on exams, so both of those resources are a valuable source of study material as well.

Be sure to bring the reader with you to the exam. We won't repeat the standard class definitions on the exam, so the reader appendix will come in handy for looking up the library interfaces.

(FYI: All the space usually left for answers was removed in order to conserve trees).

Problem 1: Templates and callback functions

a) Write the generic function KeysForMaxValue that searches for the maximum value in a map and returns the associated key(s). The function is given a map and a callback function to compare values and returns a vector containing one or more keys that are paired with the largest value in the map. The comparison callback function has the standard form: it takes two arguments and returns a negative result if the first is less than the second, zero if the two are equal, and positive otherwise. If the client doesn't provide a comparison function, a default one that applies the built-in relational operators should be used. This function should be written as a template and should work for maps storing any type of values. You may assume that the map has at least one entry.

As an example, suppose that you have initialized the map ages like this:

Map ages; ages.add("Zinnia", 3); ages.add("Rein", 4); ages.add("Kalev", 2) ages.add("Ian", 4);

Calling KeysForMaxValue(ages) returns a vector containing {"Rein", "Ian"}.

b) Use the KeysForMaxValue function from part (a) to implement the MostFrequentSeed function that returns the most frequently occurring seed from a Markov model. The Markov model is represented as in the Random Writer assignment: a map where each key is a seed and its value is a vector of characters, one following each occurrence of the seed within the input text. If there is a tie for most frequent, return a random choice from the most frequent seeds. You should use the KeysForMaxValue function and can assume it works correctly.

string MostFrequentSeed(Map<Vector > & model)

Problem 2: Linked lists The reader discusses two different Set implementations, one layered on the BST class template and another using bit vectors. For this problem you will consider instead using a sorted linked list. Here is a diagram of a linked list set containing the integer elements {10, 22, 25, 39, 57}.

10 22 25 39 57

The standard Set class template interface is given in the reader appendix. Using an internal data structure of a sorted linked list, you will implement the contains and unionWith member functions. Remember that you are writing these functions as the implementer of the Set class and thus have direct access to all its internal data structures. Your implementation must adhere to the following constraints:

  • The elements are internally stored using a singly-linked list in ascending sorted order.
  • The list does not use a dummy cell.
  • The number of elements is cached in a data member to avoid traversing the list to count.
  • contains runs in O(N) time where N is the number of elements in the set.
  • unionWith must run in O(N) time where N is the number of elements in the input sets.
  • unionWith should not call any other member functions. This is necessary in order to run in linear time.
  • The Set class must work for elements of any type.

Problem 3: Trees When implementing a binary search tree, an important efficiency concern is taking care that the tree remains balanced to ensure logarithmic performance for insert and lookup. In lecture, we briefly mentioned self-adjusting trees such as AVL that continually make minor rearrangements to prevent the tree from becoming lopsided. An alternative strategy is to wait until a problem is observed and then perform a tree rebalancing.

Write the function Rebalance that rebalances a binary search tree. After rebalancing, the tree will contain the same values as before and is still a valid binary search tree, but its nodes have been re-organized into a balanced configuration.

A few very important notes:

  • Rebalancing must take at most O(N) time where N is the number of nodes in the tree.
  • A straightforward way to meet the performance requirement is to transfer the nodes into a Vector in sorted order and then construct the balanced tree from the Vector. Be sure to consider how you can easily fill the Vector in sorted order and how having the nodes in sorted order enables you to directly and efficiently build a balanced tree.
  • You are strongly encouraged to decompose your solution into helper functions. Below, we give suggested prototypes for two helpers (one for filling the vector, another for building a tree from a vector). You are free to change/augment our suggested decomposition.
  • No nodes are created or destroyed, the existing nodes are just rearranged. This means you should not new or delete nodes.

**struct nodeT { string data; nodeT *left, *right; }; // suggested prototypes for helper functions void FillVector(nodeT *t, Vector<nodeT > &v); nodeT * BuildTree(Vector<nodeT > &v, int startIndex, int stopIndex);

*void Rebalance(nodeT & t)

Problem 4: Graphs and graph algorithms A dominating set of a graph is a subset of the nodes such that those nodes along with their immediate neighbors constitute all graph nodes. That is, every node in the graph is either in the dominating set or is a neighbor of a node in the dominating set. In the graph diagrammed below, the black nodes mark a dominating set for the graph. Other dominating sets are also possible. (Each node is labeled with the number of neighbors to facilitate tracing the algorithm below.)

3 3

3

2

(^2 )

2

1

(^51)

4

Often the goal is to find the absolute minimum size dominating set , but it is known that this is a computationally difficult task – too expensive for most graphs. Here is a greedy approximation algorithm to build a small dominating set (not guaranteed to produce the optimal result):

  • The set starts empty
  • Consider each graph node in order of decreasing number of neighbors (e.g. start by examining the node with the most neighbors)
  • If the node is not redundant with the set, add it to the set (a node would be redundant if it and all its neighbors are already dominated by the set)
  • Continue until the set dominates the entire graph

Implement the function FindSmallDomSet that takes the set of graph nodes and returns a subset of nodes that forms a small dominating set as found by the above algorithm.

Hints:

  • The PQueue class should be used to process nodes in order.
  • When ordering nodes by number of neighbors, ties can be broken arbitrarily.
  • The high-level Set class operations will be handy here.

*struct node { string name; Set<node > connectedTo; };

**Set<node > FindSmallDomSet(Set<node > & allNodes)

Problem 5: Class design The Calendar class organizes a personal event schedule. Here are specifications for a Calendar:

  • A Calendar tracks events scheduled according to date. Each event stores its time, duration, title, and a description.
  • The two most frequently performed operations are:
    1. displayByDate : For a given date, display all events scheduled on that date in time order.
    2. findByKeyword : For a given keyword, display a list of all events that contain that keyword in its description.
  • The Calendar must also allow adding new events, but it is not as critical to optimize this operation since it occurs much less frequently than the above operations.
  • It is desirable to be frugal with space where feasible.

For this problem, you will consider various Calendar implementation decisions. You will choose data structures and describe the algorithmic processes for the operations. You will not write code to implement the operations.

When asked to make and justify a choice, your justification should address relevant design issues such as big-O efficiency, memory use, ease of coding, scalability, and so on. Your answer will be evaluated on the data structure design and specifics of the implementation. You should clearly describe a successful and sensible strategy for meeting the requirements and provide solid justification for your choices, noting alternative strategies you considered and why they were rejected. Don't obsess over perfectly composed English; short bullets are fine.

Unless you state otherwise, we will assume these implementations for the standard classes:

Vector array (dynamically resized) Grid 2-dimensional array Stack, Queue linked list Map hash table (dynamic rehashing) BST balanced binary search tree Set BST PQueue binary heap