H37-PracticeSolution

H37-PracticeSolution - CS106B Handout #37 J Zelenski Mar...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS106B Handout #37 J Zelenski Mar 12, 2008 Practice Solution Final exam: Friday March 21 12:15-3:15pm Kresge Aud (in the Law School) Problem 1: Templates and callback functions template <typename Type> Vector<string> KeysForMaxValue(Map<Type> & map, int (cmp)(Type, Type) = OperatorCmp) { Map<Type>::Iterator itr = map.iterator(); Vector<string> keys; string key = itr.next(); // init max to first entry Type maxValue = map[key]; keys.add(key); while (itr.hasNext()) { // iterate to examine other entries string next = itr.next(); Type val = map[next]; if (cmp(val, maxValue) == 0) // if tied for max keys.add(next); // add to existing set else if (cmp(val, maxValue) > 0) { // if new max found keys.clear(); // clear set and init to this key keys.add(next); maxValue = val; } } return keys; } int CmpBySize(Vector<char> one, Vector<char> two) { return one.size() - two.size(); // cheesy but effective, subtract for -,0,+ } string MostFrequentSeed(Map<Vector<char> > & model) { Vector<string> seeds = KeysForMaxValue(model, CmpBySize); return seeds[RandomInteger(0, seeds.size()-1)]; } 2 Problem 2: Linked lists template <typename ElemType> bool Set<ElemType>::contains(ElemType elem) { for (cellT *cur = head; cur != NULL; cur = cur->next) { int sign = cmp(cur->value, elem); if (sign == 0) return true; if (sign > 0) break; } return false; } template <typename ElemType> void Set<ElemType>::unionWith(Set &otherSet) { cellT *prev = NULL; cellT *cur = head, *other = otherSet.head; while (other != NULL) { int sign = (cur == NULL ? 1 : cmp(cur->value, other->value)); if (sign == 0) { // case 1: this elem == other elem prev = cur; cur = cur->next; // advance both this and other other = other->next; } else if (sign < 0) { // case 2: this elem < other elem prev = cur;...
View Full Document

This note was uploaded on 10/12/2011 for the course CS 108 taught by Professor Smith during the Spring '11 term at Central Mich..

Page1 / 4

H37-PracticeSolution - CS106B Handout #37 J Zelenski Mar...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online