CompSci 100e 7.1 Hashing: Log (10 100 ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.

Slides:



Advertisements
Similar presentations
CPS 100, Fall Backtracking by image search.
Advertisements

CompSci 100e Program Design and Analysis II March 3, 2011 Prof. Rodger CompSci 100e, Spring
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
1 CSE 326: Data Structures Hash Tables Autumn 2007 Lecture 14.
Tirgul 7. Find an efficient implementation of a dynamic collection of elements with unique keys Supported Operations: Insert, Search and Delete. The keys.
Hashing General idea: Get a large array
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
CPS 100, Spring Analysis: Algorithms and Data Structures l We need a vocabulary to discuss performance and to reason about alternative algorithms.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
CompSci 100E 10.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
CPS 100, Spring From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
CompSci 100 Prog Design and Analysis II Sept 16, 2010 Prof. Rodger CompSci 100, Fall
CompSci 100E 12.1 Solving Problems Recursively  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
TECH Computer Science Dynamic Sets and Searching Analysis Technique  Amortized Analysis // average cost of each operation in the worst case Dynamic Sets.
CompSci 100e Program Design and Analysis II March 29, 2011 Prof. Rodger CompSci 100e, Spring20111.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 9: Searching Data Structures.
1 CSE 326: Data Structures: Hash Tables Lecture 12: Monday, Feb 3, 2003.
CompSci 100e 6.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a.
CPS Searching, Maps,Tries (hashing) l Searching is a fundamentally important operation  We want to search quickly, very very quickly  Consider.
Compsci 100, Fall From Recursion to Self Reference public int calc(int n){ return n*calc(n-1); } l What is the Internet?  A network of networks.
CPS 100, Fall GridGame APT How would you solve this problem using recursion?
Chapter 5: Hashing Part I - Hash Tables. Hashing  What is Hashing?  Direct Access Tables  Hash Tables 2.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
CPS Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze  Certain mazes can be solved using the “right-hand”
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables IV.
CompSci 100e 6.1 Plan for the week l More recursion examples l Backtracking  Exhaustive incremental search  When we a potential solution is invalid,
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
Hashing 1 Hashing. Hashing 2 Hashing … * Again, a (dynamic) set of elements in which we do ‘search’, ‘insert’, and ‘delete’ n Linear ones: lists, stacks,
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems.
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
CompSci Analyzing Algorithms  Consider three solutions to SortByFreqs, also code used in Anagram assignment  Sort, then scan looking for changes.
CompSci 100E 15.1 What is a Binary Search?  Magic!  Has been used a the basis for “magical” tricks  Find telephone number ( without computer ) in seconds.
CompSci 100 Prog Design and Analysis II Oct 26, 2010 Prof. Rodger CPS 100, Fall
CompSci Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze ä Certain mazes can be solved using the.
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
Recursion Fundamentals of Recursion l Base case (aka exit case)  Simple case that can be solved with no further computation  Does not make a recursive.
CPS Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze ä Certain mazes can be solved using the “right-hand”
Chapter 9 Recursion © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
CPS Searching, Maps, Tables (hashing) l Searching is a fundamentally important operation  We want to search quickly, very very quickly  Consider.
CPS Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply.
A Computer Science Tapestry 10.1 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit ä Allows many complex problems.
CPS Searching, Maps, Tables l Searching is a fundamentally important operation ä We want to do these operations quickly ä Consider searching using.
CSC 143T 1 CSC 143 Highlights of Tables and Hashing [Chapter 11 p (Tables)] [Chapter 12 p (Hashing)]
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CPS 100, Spring Search, Backtracking,Heuristics l How do you find a needle in a haystack?  How does a computer play chess?  Why would you write.
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
CPS Searching, Maps, Tables (hashing) l Searching is a fundamentally important operation  We want to search quickly, very very quickly  Consider.
CompSci 100e 7.1 Plan for the week l Recurrences  How do we analyze the run-time of recursive algorithms? l Setting up the Boggle assignment.
Game playing Types of games Deterministic vs. chance
Searching, Maps,Tries (hashing)
Backtracking, Search, Heuristics
Analysis: Algorithms and Data Structures
Plan for the Week Review for Midterm Source code provided
Solving Problems Recursively
Tools: Solve Computational Problems
Announcements Final Exam on August 17th Wednesday at 16:00.
CSE373: Data Structures & Algorithms Lecture 14: Hash Collisions
CSE373: Data Structures & Algorithms Lecture 14: Hash Collisions
Announcements Final Exam on August 19th Saturday at 16:00.
Announcements Final Exam on December 25th Monday at 16:00.
Announcements HW3 grades will be announced this week
Solving Problems Recursively
Backtracking, Search, Heuristics
Solving Problems Recursively
Backtracking, Search, Heuristics
Presentation transcript:

CompSci 100e 7.1 Hashing: Log ( ) is a big number l Comparison based searches are too slow for lots of data  How many comparisons needed for a billion elements?  What if one billion web-pages indexed? l Hashing is a search method: average case O(1) search  Worst case is very bad, but in practice hashing is good  Associate a number with every key, use the number to store the key Like catalog in library, given book title, find the book l A hash function generates the number from the key  Goal: Efficient to calculate  Goal: Distributes keys evenly in hash table

CompSci 100e 7.2 Hashing details l There will be collisions, two keys will hash to the same value  We must handle collisions, still have efficient search  What about birthday “paradox”: using birthday as hash function, will there be collisions in a room of 25 people? l Several ways to handle collisions, in general array/vector used  Linear probing, look in next spot if not found Hash to index h, try h+1, h+2, …, wrap at end Clustering problems, deletion problems, growing problems  Quadratic probing Hash to index h, try h+1 2, h+2 2, h+3 2, …, wrap at end Fewer clustering problems  Double hashing Hash to index h, with another hash function to j Try h, h+j, h+2j, … n-1

CompSci 100e 7.3 Chaining with hashing l With n buckets each bucket stores linked list  Compute hash value h, look up key in linked list table[h]  Hopefully linked lists are short, searching is fast  Unsuccessful searches often faster than successful Empty linked lists searched more quickly than non-empty  Potential problems? l Hash table details  Size of hash table should be a prime number  Keep load factor small: number of keys/size of table  On average, with reasonable load factor, search is O(1)  What if load factor gets too high? Rehash or other method

CompSci 100e 7.4 Hashing problems l Linear probing, hash(x) = x, (mod tablesize)  Insert 24, 12, 45, 14, delete 24, insert 23 (where?) l Same numbers, use quadratic probing (clustering better?) l What about chaining, what happens?

CompSci 100e 7.5 What about hash functions l Hashing often done on strings, consider two alternatives public static int hash(String s) { int k, total = 0; for(k=0; k < s.length(); k++){ total += s.charAt(k); } return total; } Consider total += (k+1)*s.charAt(k), why might this be better?  Other functions used, always mod result by table size l What about hashing other objects?  Need conversion of key to index, not always simple  Ever object has method hashCode()!

CompSci 100e 7.6 Tools: Solving Computational Problems l Algorithmic techniques and paradigms  Brute-force/exhaustive, greedy algorithms, dynamic programming, divide-and-conquer, …  Transcend a particular language  Designing algorithms, may change when turned into code l Programming techniques and paradigms  Recursion, memo-izing, compute-once/lookup, tables, …  Transcend a particular language  Help in making code work Avoid software problems (propagating changes, etc.) Avoid performance problems

CompSci 100e 7.7 Quota Exceeded l You’re running out of disk space  Buy more  Compress files  Delete files l How do you find your “big” files?  What’s big?  How do you do this?

CompSci 100e 7.8 Recursive structure matches code public static long THRESHOLD = L; // one million bytes public static void findBig(File dir, String tab) { File[] dirContents = dir.listFiles(); System.out.println(tab+"**:"+dir.getPath()); for(File f : dirContents){ if (f.isDirectory()) { findBig(f,tab+"\t"); } else { if (f.length() > THRESHOLD){ System.out.printf("%s%s%8d\n",tab,f.getName(), f.length()); } Does findBig call itself?

CompSci 100e 7.9 Solving Problems Recursively l Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved simply  Elegance and understanding in code often leads to better programs: easier to modify, extend, verify (and sometimes more efficient!!)  Sometimes recursion isn’t appropriate, when it’s bad it can be very bad---every tool requires knowledge and experience in how to use it l The basic idea is to get help solving a problem from coworkers (clones) who work and act like you do  Ask clone to solve a simpler but similar problem  Use clone’s result to put together your answer l Need both concepts: call on the clone and use the result

CompSci 100e 7.10 Print words read, but print backwards l Could store all the words and print in reverse order, but …  Probably the best approach, recursion works too public void printReversed(Scanner s){ if (s.hasNext()){ // reading succeeded? String word = s.next(); // store word printReversed(s); // print rest System.out.println(word); // print the word } The function printReversed reads a word, prints the word only after the clones finish printing in reverse order  Each clone has own version of the code, own word variable  Who keeps track of the clones?  How many words are created when reading N words? Can we do better?

CompSci 100e 7.11 Exponentiation l Computing x n means multiplying n numbers (or does it?)  What’s the simplest value of n when computing x n ?  If you want to multiply only once, what can you ask a clone? public static double power(double x, int n){ if (n == 0){ return 1.0; } return x * power(x, n-1); } l Number of multiplications?  Note base case: no recursion, no clones  Note recursive call: moves toward base case (unless …)

CompSci 100e 7.12 Faster exponentiation l How many recursive calls are made to computer ?  How many multiplies on each call? Is this better? public static double power(double x, int n){ if (n == 0) { return 1.0; } double semi = power(x, n/2); if (n % 2 == 0) { return semi*semi; } return x * semi * semi; } l What about an iterative version of this function?

CompSci 100e 7.13 Recursive example 1 double power(double x, int n) // post: returns x^n { if (n == 0) { return 1.0; } return x * power(x, n-1); } x: n: Return value:

CompSci 100e 7.14 Recursive example 2 double fasterPower(double x, int n) // post: returns x^n { if (n == 0) { return 1.0; } double semi = fasterPower(x, n/2); if (n % 2 == 0) { return semi*semi; } return x * semi * semi; } x: n: Return value:

CompSci 100e 7.15 Recursive example 3 String mystery(int n) { if (n < 2) { return "" + n; WriteBinary(-n); } else { return mystery(n / 2) + (n % 2); } n: Return value:

CompSci 100e 7.16 Back to Recursion l Recursive functions have two key attributes  There is a base case, sometimes called the exit case, which does not make a recursive call See print reversed, exponentiation  All other cases make a recursive call, with some parameter or other measure that decreases or moves towards the base case Ensure that sequence of calls eventually reaches the base case “Measure” can be tricky, but usually it’s straightforward l Example: finding large files in a directory (on a hard disk)  Why is this inherently recursive?  How is this different from exponentation?

CompSci 100e 7.17 Thinking recursively l Problem: find the largest element in an array  Iteratively: loop, remember largest seen so far  Recursive: find largest in [1..n), then compare to 0 th element public static double max(double[] a){ double maxSoFar = a[0]; for(int k=1; k < a.length; k++) { maxSoFar = Math.max(maxSoFar,a[k]); } return maxSoFar; }  In a recursive version what is base case, what is measure of problem size that decreases (towards base case)?

CompSci 100e 7.18 Recursive Max public static double recMax(double[] a, int index){ if (index == a.length-1){ // last element, done return a[index]; } double maxAfter = recMax(a,index+1); return Math.max(a[index],maxAfter); } l What is base case (conceptually)?  Do we need variable maxAfter ? We can use recMax to implement arrayMax as follows return recMax(a,0); Recursive methods sometimes use extra parameters; helper methods set this up

CompSci 100e 7.19 Recognizing recursion: public static void change(String[] a, int first, int last){ if (first < last) { String temp = a[first]; // swap a[first], a[last] a[first] = a[last]; a[last] = temp; change(a, first+1, last-1); } // original call (why?): change(a, 0, a.length-1); l What is base case? (no recursive calls) l What happens before recursive call made? l How is recursive call closer to the base case? Recursive methods sometimes use extra parameters; helper methods set this up

CompSci 100e 7.20 The Power of Recursion: Brute force l Consider the TypingJob APT problemn: What is minimum number of minutes needed to type n term papers given page counts and three typists typing one page/minute? (assign papers to typists to minimize minutes to completion)  Example: {3, 3, 3,5,9,10,10} as page counts l How can we solve this in general? Suppose we're told that there are no more than 10 papers on a given day.  How does this constraint help us?  What is complexity of using brute-force?

CompSci 100e 7.21 Recasting the problem l Instead of writing this function, write another and call it min minutes to type papers in pages int bestTime(int[] pages) { } l What cases do we consider in function below? int best(int[] pages, int index, int t1, int t2, int t3) // returns min minutes to type papers in pages // starting with index-th paper and given // minutes assigned to typists, t1, t2, t3 { } return best(pages,0,0,0,0);

CompSci 100e 7.22 Recursive example: BlobCount l How do we find images? Components? Paths?  Create information from data

CompSci 100e 7.23 From programming techniques to Java l Is recursion a language independent concept?  Do all languages support recursion?  What are the issues in terms of computer/compiler/runtime support? l We use a language and its libraries, do we study them?  Should we know how to implement ArrayList What are the building blocks, what are our tools  Should we know how to implement different sorts Should we know how to call existing sorts

CompSci 100e 7.24 Print words entered, but backwards l Can use an ArrayList, store all the words and print in reverse order  Probably the best approach, recursion works too public void printReversed(Scanner s){ if (s.hasNext()){ // reading succeeded? String word = s.next(); // store word printReversed(s); // print rest System.out.println(word);// print the word } The function printReversed reads a word, prints the word only after the clones finish printing in reverse order  Each clone has own version of the code, own word variable  Who keeps track of the clones?  How many words are created when reading N words? What about when ArrayList used?

CompSci 100e 7.25 Why we study recurrences/complexity? l Tools to analyze algorithms l Machine-independent measuring methods l Familiarity with good data structures/algorithms l What is CS person: programmer, scientist, engineer? scientists build to learn, engineers learn to build l Mathematics is a notation that helps in thinking, discussion, programming

CompSci 100e 7.26 Recurrences l Summing Numbers int sum(int n) { if (0 == n) return 0; else return n + sum(n-1); } l What is complexity? justification? l T(n) = time to compute sum for n T(n) = T(n-1) + 1 T(0) = 1 l instead of 1, use O(1) for constant time  independent of n, the measure of problem size

CompSci 100e 7.27 Solving recurrence relations l plug, simplify, reduce, guess, verify? T(n) = T(n-1) + 1 T(0) = 1 T(n) = T(n-k) + k find the pattern! Now, let k=n, then T(n) = T(0)+n = 1+n l get to base case, solve the recurrence: O(n) T(n-1) = T(n-1-1) + 1 T(n) = [T(n-2) + 1] + 1 = T(n-2)+2 T(n-2) = T(n-2-1) + 1 T(n) = [(T(n-3) + 1) + 1] + 1 = T(n-3)+3

CompSci 100e 7.28 Complexity Practice l What is complexity of Build ? (what does it do?) ArrayList build(int n) { if (0 == n) return new ArrayList (); // empty ArrayList list = build(n-1); for(int k=0;k < n; k++){ list.add(n); } return list; } l Write an expression for T(n) and for T(0), solve.

CompSci 100e 7.29 Recognizing Recurrences l Solve once, re-use in new contexts  T must be explicitly identified  n must be some measure of size of input/parameter T(n) is the time for quicksort to run on an n-element vector T(n) = T(n/2) + O(1) binary search O( ) T(n) = T(n-1) + O(1) sequential search O( ) T(n) = 2T(n/2) + O(1) tree traversal O( ) T(n) = 2T(n/2) + O(n) quicksort O( ) T(n) = T(n-1) + O(n) selection sort O( ) l Remember the algorithm, re-derive complexity n log n n log n n n2n2

CompSci 100e 7.30 Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze  Certain mazes can be solved using the “right-hand” rule  Other mazes, e.g., with islands, require another approach  If you have “markers”, leave them at intersections, don’t explore the same place twice l What happens if you try to search the web, using links on pages to explore other links, using those links to …  How many web pages are there?  What rules to webcrawlers/webspiders follow? Who enforces the rules? l Keep track of where you’ve been don’t go there again  Any problems with this approach?

CompSci 100e 7.31 Backtracking with Boggle l Boggle tm played on 4x4 board  Other sizes possible  Form words by connecting letters horizontally, vertically, diagonally  Cannot re-use letters (normally) l Two approaches  Build words from connections, find partial words in dictionary  Look up every word in the dictionary on the board l Which is better? How is backtracking used?

CompSci 100e 7.32 Classic problem: N queens l Can queens be placed on a chess board so that no queens attack each other?  Easily place two queens  What about 8 queens? l Make the board NxN, this is the N queens problem  Place one queen/column  # different tries/column? l Backtracking  Use “current” row in a col  If ok, try next col  If fail, back-up, next row

CompSci 100e 7.33 Backtracking idea with N queens l Try to place a queen in each column in turn  Try first row in column C, if ok, move onto next column  If solved, great, otherwise try next row in column C, place queen, move onto the next column Must unplace the placed queen to keep going l What happens when we start in a column, where to start?  If we fail, move back to previous column (which remembers where it is/failed)  When starting in a column anew, start at beginning When backing up, try next location, not beginning l Backtracking in general, record an attempt go forward  If going forward fails, undo the record and backup

CompSci 100e 7.34 Basic ideas in backtracking search l We need to be able to enumerate all possible choices/moves  We try these choices in order, committing to a choice  If the choice doesn’t pan out we must undo the choice This is the backtracking step, choices must be undoable l Process is inherently recursive, so we need to know when the search finishes  When all columns tried in N queens  When all board locations tried in boggle  When every possible moved tried in Tic-tac-toe or chess? Is there a difference between these games? l Summary: enumerate choices, try a choice, undo a choice, this is brute force search: try everything

CompSci 100e 7.35 Computer v. Human in Games l Computers can explore a large search space of moves quickly  How many moves possible in chess, for example? l Computers cannot explore every move (why) so must use heuristics  Rules of thumb about position, strategy, board evaluation  Try a move, undo it and try another, track the best move l What do humans do well in these games? What about computers?  What about at Duke?