26S-CS106X-Practice-Key

26S-CS106X-Practice-Key - CS106X Autumn 2010 Handout 26S...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS106X Handout 26S Autumn 2010 October 30th, 2010 CS106X Practice Solution Solution 1: Acronyms void ReadIntoMap(ifstream& in, Map<Vector<string> >& map) { Scanner s; s.setSpaceOption(Scanner::IgnoreSpaces); while (true) { string line; getline(in, line); if (in.fail()) break; s.setInput(line); string acronym = ""; while (s.hasMoreTokens()) acronym += s.nextToken()[0]; map[acronym].add(line); // [] creates empty vector if needed } } double PercentConfusing(Map<Vector<string> >& map) { int numConfusing = 0; foreach (string key in map) { if (map[key].size() > 1) numConfusing++; } return double(numConfusing)/map.size(); } Solution 2: HTML Entitles string RestoreString(string str, Map<char>& entityMap) { string translation; translation.reserve(str.size()); // optional, preallocates space // cpos stands for 'c'haracter 'pos'ition for (int cpos = 0; cpos < str.size(); cpos++) { if (str[cpos] == '&') { int scpos = str.find(';', cpos + 1); string entityCore = str.substr(cpos + 1, scpos - cpos - 1); if (entityMap.containsKey(entityCore)) { translation += entityMap[entityCore]; } else { translation += '&' + entityCore + ';'; } cpos = scpos; } else { translation += str[cpos]; } } return translation; }
Background image of page 1

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

View Full DocumentRight Arrow Icon
Solution 3: Pascal’s Travels int NumPaths(Grid<int>& board) { return NumPaths(board, 0, 0); } int NumPaths(Grid<int>& board, int row, int col) { if ((row == board.numRows() – 1) && (col == board.numCols() – 1)) return 1; if (!OnBoard(board, row, col)) return 0; if (board[row][col] == 0) return 0; int hop = board[row][col]; board[row][col] = 0; int count = NumPaths(board, row + hop, col) + NumPaths(board, row – hop, col) + NumPaths(board, row, col + hop) + NumPaths(board, row, col – hop); board[row][col] = hop; return count; } Solution 4: Longest Increasing Subsequence
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

26S-CS106X-Practice-Key - CS106X Autumn 2010 Handout 26S...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online