google applied cs - day 3

19
Google Applied CS with Android

Upload: harsh-vakharia

Post on 22-Feb-2017

193 views

Category:

Education


0 download

TRANSCRIPT

Google

Applied CSwith Android

High Time

Ghost

How-to1. Build dictionary

2. Set button click listeners

3. Decide the turn

Decide the turnif (user's turn) { listen to onKeyUp -> (k) { if k is a valid letter { append it to TextView } else ignore }} else { if word is of length 4 or more && it is a valid word { Computer wins } else { put next character }}

Put next characterIt should form a valid word because this is a computer!

Ta-da !while (low < high) { mid = (low + high) / 2; t = words.get(mid); if(t.startsWith(prefix)) { return t; } else if(prefix.compareTo(t) > 0) { // LHS is bigger low = mid + 1; } else { // RHS is bigger high = mid - 1; }}

Best case: O(1)Average/Worst case:

O(log n)

Tri !re(tri)eval

Basics1. HashMap<Character, TrieNode> children2. root.add(word)3. root.isWord(word)4. root.getAnyWordStartingWith(word)

Add a word to Trievoid add(String s, int position) { if (position >= s.length()) return;

char c = s.charAt(position); TrieNode n = children.get(c);

if (n == null) { n = new TrieNode(); children.put(c, n); }

if (position == s.length() - 1) { n.isWord = true; }

n.add(s, position + 1);}

And a bit of method overloading

void add(String s) { add(s, 0)}

void add(String s, int position) { ... }

Same logic, different application1. root.isWord(word)2. root.getAnyWordStartingWith(word)

Fast Dictionary !An efficient lookup structure

This is it for today

Any doubts?