My 2003 AP-A Solutions
Problem #1
void CollegeGroup::UpdateTuition(const apstring & collegeName, int newTuition)
{
for (int k = 0; k < myColleges.length(); k++)
if (collegeName == myColleges[k].Name())
{
myColleges[k].SetTuition(newTuition);
return;
}
}
apvector<College> CollegeGroup::GetCollegeList(const apstring & region, int low, int high)
{
apvector<College> colleges(myColleges.length());
int ctr = 0;
for (int k = 0; k < myColleges.length(); k++)
if (region == myColleges[k].Region() &&
myColleges[k].Tuition() >= low && myColleges[k].Tuition() <= high)
{
colleges[ctr] = myColleges[k];
ctr++;
}
colleges.resize(ctr);
return colleges;
}
Problem #2
void Company::ProcessRetirements()
{
apvector<Employee> newEmpList(empList.length());
int ctr = 0;
for (int k = 0; k < empList.length(); k++)
{
if (EmployeeIsEligible(empList[k]))
{
salaryBudget -= empList[k].Salary();
}
else
{
newEmpList[ctr] = empList[k];
ctr++;
}
}
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;
}
Problem #3
bool TreasureMap::HasTreasure(int row, int col) const
{
if (row >= 0 && row < NumRows() &&
col >= 0 && col < NumCols() &&
myGrid[row][col])
return true;
return false;
}
int TreasureMap::NumAdjacent(int row, int col) const
{
int ctr = 0;
if (HasTreasure(row-1,col))
ctr++;
if (HasTreasure(row-1,col-1))
ctr++;
if (HasTreasure(row,col-1))
ctr++;
if (HasTreasure(row+1,col))
ctr++;
if (HasTreasure(row+1,col+1))
ctr++;
if (HasTreasure(row,col+1))
ctr++;
if (HasTreasure(row-1,col+1))
ctr++;
if (HasTreasure(row+1,col-1))
ctr++;
return ctr;
}
apmatrix<int> computecounts(const TreasureMap & themap)
{
apmatrix<int> map(themap.NumRows(), themap.NumCols());
for (int r = 0; r < themap.NumRows(); r++)
for (int c = 0; c < themap.NumCols(); c++)
if (themap.HasTreasure(r,c))
map[r][c] = 9;
else
map[r][c] = themap.NumAdjacent(r,c);
return map;
}
Problem #4
int Environment::NumAlgaeAt(const Position & pos) const
{
if (! InRange(pos))
{
cerr << "error, attempt to access algae at non-existent: " << pos << endl;
return -1;
}
return myAlgae[pos.Row()][pos.Col()];
}
void Fish::Act(Environment & env)
{
if (env.NumAlgaeAt(myPos) > 0)
{
env.RemoveAlgae(myPos, 1);
myStepsSinceFed = 0;
env.Update(myPos, *this);
}
else if (myStepsSinceFed == 3)
{
env.RemoveFish(myPos);
}
else
{
myStepsSinceFed++;
Move(env);
env.Update(myPos, *this);
}
}
Position Fish::MostAlgae(const Environment & env, const Neighborhood & nbrs) const
{
if (nbrs.Size() <= 0)
return Position();
Position maxpos = nbrs.Select(0);
int maxAlgae = env.NumAlgaeAt(maxpos);
for (int k = 1; k < nbrs.Size(); k++)
if (env.NumAlgaeAt(nbrs.Select(k)) > maxAlgae)
maxpos = nbrs.Select(k);
return maxpos;
}