My 2003 AP-AB Solutions
Problem #1
void Company::ProcessRetirements(const apvector & claimants)
{
apvector<Employee> newEmpList(empList.length());
int ctr = 0, k = 0;
for (int c = 0; c < claimants.length(); c++)
{
while (claimants[c].ID() != empList[k].ID())
{
newEmpList[ctr] = empList[k];
ctr++;
k++;
}
if (EmployeeIsEligible(claimants[c]))
{
salaryBudget -= empList[k].Salary();
}
else
{
newEmpList[ctr] = empList[k];
ctr++;
}
k++;
}
empList = newEmpList;
empList.resize(ctr);
}
bool Company::EmployeeIsEligible(const Employee & emp) const
{
int count = 0;
if(emp.Age() >= retireAge)
count++;
if(emp.YearsOnJob() >= retireYears)
count++;
if(emp.Salary() >= retireSalary)
count++;
return count >= 2;
}
O(N) - Outer loop goes N times, inner is not related to outer loop
and it runs a total of N times.
Problem #2
DrawerNode * FilingCabinet::FindDrawer(int studentID) const
{
DrawerNode * ptr = drawerList;
while (studentID > ptr->drawerMaxID)
ptr = ptr->next;
return ptr;
}
void FilingCabinet::RemoveStudent(int studentID)
{
DrawerNode * drawerPtr = FindDrawer(studentID);
StudentNode * sPtr = drawerPtr->studentList;
StudentNode * before = NULL;
while (sPtr != NULL && sPtr->idNum != studentID)
{
before = sPtr;
sPtr = sPtr->next;
}
if (sPtr != NULL)
{
if (before == NULL)
drawerPtr->studentList = sPtr->next;
else
before->next = sPtr->next;
delete sPtr;
}
}
Problem #3
void Environment::AllFishHelper(Node * root, apvector<Fish> & fishList, int & index) const
{
if (root != NULL)
{
AllFishHelper(root->left, fishList, index);
fishList[index] = root->theFish;
index++;
AllFishHelper(root->right, fishList, index);
}
}
void Environment::AddFishHelper(Node * root, const Fish & fsh) const
{
if (root == NULL)
{
root = new Node(fsh);
}
else
{
Node * p = root;
Node * parent = NULL;
while (p != NULL)
{
parent = p;
if (fsh < p->theFish)
p = p->left;
else
p = p->right;
}
Node * f = new Node(fsh);
if (fsh < parent->theFish)
parent->left = f;
else
parent->right = f;
}
}
Problem #4
class StringTokenizer
{
public:
StringTokenizer(const apstring & s);
int NumTokens() const;
apstring GetToken(int index) const;
private:
apvector<apstring> myTokens;
};
apstring CreateAcronym(const apstring & str)
{
StringTokenizer st(str);
apstring acronym = "";
for (int k = 0; k < st.NumTokens(); k++)
{
apstring token = st.GetToken(k);
acronym += token[0];
}
return acronym;
}