Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more ➡
Standard view
Full view
of .
×
0 of .
Results for:
P. 1
h27 practice soln

# h27 practice soln

Ratings: 0|Views: 171|Likes:

### Availability:

See More
See less

02/01/2013

pdf

text

original

CS106B
Handout #27
Yves Lu
July 24, 2008
Midterm practice solutions
Midterm Exam:
Monday, July 28th, 7-9pm
TBA
Problem 1: C++ coding
void FindHiddenWord(string hidden, ifstream &inFile)
{
string line;
while(true)

{
getline(inFile, line);
if(inFile.fail()) break;
string removed;
for(int i = 0; i < line.length(); i++)
{

if(isalpha(line[i]))
removed += line[i];
}removed = ConvertToLowerCase(removed);
if(removed.find(hidden) != string::npos)
{
cout << line << endl;
}
}
}Problem 2: Recursion
double BestChanceOfSurvival(Grid<Tile> &treasureMap, int startRow,
int startCol)

{
Grid<bool> marks;
marks.resize(treasureMap.numRows(), treasureMap.numCols());
for(int i = 0; i < marks.numRows(); i++)

for(int j = 0; j < marks.numCols(); j++)
marks(i, j) = false;
return(RecBestChanceOfSurvival(treasureMap, marks, startRow, startCol));
}
\u20132 \u2013
double RecBestChanceOfSurvival(Grid<Tile> &treasureMap, Grid<bool> &marks,
int startRow, int startCol)

{
/* make sure to check bounds before anything else */
if(startRow < 0 || startRow >= treasureMap.numRows() ||

startCol < 0 || startCol >= treasureMap.numCols())
{
return(0);
}if(marks(startRow, startCol))
{
return(0);
}if(treasureMap(startRow, startCol).isTreasure())
{
return(treasureMap(startRow, startCol).getChanceOfSurvival());
}double max = 0;

marks(startRow, startCol) = true;
for(int i = -1; i <= 1; i++)
{

for(int j = -1; j <= 1; j++)
{
double cur = RecBestChanceOfSurvival(treasureMap, marks, startRow + i,

startCol + j);
if(cur > max)
{

max = cur;
}
}
}marks(startRow, startCol) = false;
return(treasureMap(startRow, startCol).getChanceOfSurvival() * max);
}
\u20133 \u2013
Problem 3: Client use of classes
string FindMostCommon(Vector<Stack<string> *> &loots)
{
Map<int> counts;
for(int i = 0; i < loots.size(); i++)

{
Stack<string> tmp;
Stack<string> * cur = loots[i];

while(!cur->isEmpty())

{
string item = cur->pop();
if(counts.containsKey(item))
{

counts[item]++;
}else
{
counts[item] = 1;
}tmp.push(item);
}while(!tmp.isEmpty())
{
cur->push(tmp.pop());
}
}string maxKey, curKey;

int max = 0;
Map<int>::Iterator iter = counts.iterator();
while(iter.hasNext())
{

curKey = iter.next();
if(counts[curKey] > max)
{

maxKey = curKey;
max = counts[curKey];
}
}return(maxKey);
}

## Activity (1)

### Showing

AllMost RecentReviewsAll NotesLikes