11S-Section-Solution

11S-Section-Solution - } return num; } 2 int...

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

View Full Document Right Arrow Icon
CS106X Handout 11S Autumn 2010 September 29 th through October 1 st , 2010 Section Solution Solution 1: Look And Say string LookAndSay(string before) { string after; int len = before.size(); int pos = 0; while (pos < len) { char ch = before[pos]; int count = 1; while ((pos + count < len) && (before[pos + count] == ch)) { count++; } after += count + '0'; after += ch; pos += count; } return after; } Solution 2: http://tinyurl.com static const int kTinyURLBase = 36; string TinyURLConvertNumber(int num) { string code; // default constructed to the empty string while (num > 0) { int digit = num % kTinyURLBase; code = ConvertDigit(digit) + code; num /= kTinyURLBase; } return code; } char ConvertDigit(int digit) { if (digit < 10) return '0' + digit; return 'a' + digit - 10; } int TinyURLRecoverNumber(string code) { int num = 0; for (int i = 0; i < code.size(); i++) { num = kTinyURLBase * num + ConvertChar(code[i]);
Background image of page 1

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

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: } return num; } 2 int ConvertChar(char ch) { if (isdigit(ch)) return ch - '0'; return ch - 'a' + 10; } Solution 3: Maximizing Game Score int ComputeMaxScore(Grid<int>& board) { int prev = max(board[0][0], board[1][0]); if (board.numCols() == 1) return prev; int curr = max(prev, max(board[0][1], board[1][1])); if (board.numCols() == 2) return curr; for (int col = 2; col < board.numCols(); col++) { int next = max(curr, prev + max(board[0][col], board[1][col])); prev = curr; curr = next; } return curr; } Solution 4: String Explosions Vector<string> Explode(string str, char delim) { Vector<string> explosion; string cluster; str += delim; // last cluster gets appended w/ minimal special casing for (int i = 0; i < str.size(); i++) { if (str[i] == delim) { explosion.add(cluster); cluster.clear(); // cluster = "" works, too } else { cluster += str[i]; } } return explosion; }...
View Full Document

This note was uploaded on 01/13/2011 for the course CS 106X taught by Professor Cain,g during the Fall '08 term at Stanford.

Page1 / 2

11S-Section-Solution - } return num; } 2 int...

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

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