Member-only story
C++ Datastructures and Algorithms Final Exam Solutions
2 min readMay 31, 2022
- Assume the following variable declarations:
int foo = 0;
int *ptr = &foo;
What statements will change the value of foo to 1?
(*ptr)++;foo++;
2. Write a function countMatches which compares 2 C strings and count the number of matching characters.
void countMatches(const char *str1, const char *str2, int &count) {
int count = 0;
while (*str1 != '\0' &&*str2 != '\0') {
if (*str1 == *str2) {
count++;
}
str1++;
str2++;
}
}
3. Design the class Goldfish, which models a creature that is intelligent enough to remember capacity characters at a time.
(a) Define the constructor
Goldfish(int capacity) {if (capacity < 0){m_capacity = 3;} else if (capacity > 10){m_capacity = 10;}m_amount = 0;forget();}
(b) Implement remember. Store the character c into m_memory. If you already have m_capacity characters memorized, then discard the oldest character in m_memory to open up a free slot. (This is an example of LRU (Least Recently Used) replacement.)
void Goldfish::remember(char c){if (m_amount == m_capacity){