cs31final

# cs31final - UCLA Computer Science 31 Spring 2009 Final...

This preview shows pages 1–5. Sign up to view the full content.

UCLA Computer Science 31 Spring 2009 Final Review Problems The solution will be uploaded at http://www.cs.ucla.edu/~schoi/cs31 after the discussion. 1. Fill in the line appropriately to complete the out function, such that it outputs “out” on the screen (without quotes). The line of code you write must not use any brackets, and should copy a character from “computer”. void out(char* str, char* &ptr) { ptr = new char[4]; *ptr = str[1]; str += 4; ptr[1] = *str; ptr++; ________________________ ptr += 2; ptr[0] = '\0'; ptr -= 3; } int main() { char* word = "computer"; char* newWord; out(word, newWord); cout << newWord << endl; delete[] newWord; return 0; }

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

View Full Document
2. Design the class Goldfish , which models a creature intelligent enough to remember at most capacity characters at a time. Class Goldfish { public: Goldfish(int capacity); ~Goldfish(); void remember(char c); void forget(); void printMemory() const; // prints the content of m_memory private: char* m_memory; // pointer to memory int m_amount; // # chars remembered int m_capacity; // # chars this fish can remember }; (a) Define the constructor. Dynamically allocate capacity ‐many characters to m_memory . Initialize m_memory with dot(‘.’)s. If capacity is not positive, then set it to 3 by default. Remember to set the m_capacity . (b) Implement remember . Store the character c into m_memory . If remembering a new character makes the total number of remembered characters exceed m_capacity , then discard the oldest character from m_memory to open up a free slot. (This is an example of LRU (Least Recently Used) replacement policy.)
(c) Implement forget . Clear memory by filling dot(‘.’)s into m_memory . (d) Implement the destructor. To clarify, here is how a Goldfish object can be used: int main() { Goldfish nemo(3); nemo.remember(‘a’); nemo.printMemory(); // prints “a. .” nemo.remember(‘b’); nemo.remember(‘c’); nemo.printMemory(); // prints “abc” (or any permutation of it) nemo.remember(‘d’); nemo.printMemory(); // prints “bcd” (or any permutation of it) nemo.forget(); nemo.printMemory(); // prints “. ..” return 0; }

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

View Full Document
3. We’ll define Aquarium class, where Goldfish can live. int MAX_FISH = 20;
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 11

cs31final - UCLA Computer Science 31 Spring 2009 Final...

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

View Full Document
Ask a homework question - tutors are online