CPS 100e, Spring 2010 7.1 Day, Week, Month Overview l Backtracking p/review  Boggle  APT l Assignment review  Boggle  APT l PQ Overview.

Slides:



Advertisements
Similar presentations
Michael Alves, Patrick Dugan, Robert Daniels, Carlos Vicuna
Advertisements

COL 106 Shweta Agrawal and Amit Kumar
Chapter 4: Trees Part II - AVL Tree
CPS 100, Fall Backtracking by image search.
CompSci 100e Program Design and Analysis II March 3, 2011 Prof. Rodger CompSci 100e, Spring
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
1 Adversary Search Ref: Chapter 5. 2 Games & A.I. Easy to measure success Easy to represent states Small number of operators Comparison against humans.
1 HEAPS & PRIORITY QUEUES Array and Tree implementations.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
COMP 103 Priority Queues, Partially Ordered Trees and Heaps.
CPS 100, Fall YAQ, YAQ, haha! (Yet Another Queue) l What is the dequeue policy for a Queue?  Why do we implement Queue with LinkedList Interface.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
1 CSC 421: Algorithm Design Analysis Spring 2014 Transform & conquer  transform-and-conquer approach  presorting  balanced search trees, heaps  Horner's.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
CPS 100, Fall PF-AT-EOS l Data compression  Seriously important, why? l Priority Queue  Seriously important, why? l Assignment overview  Huff.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
P p Chapter 10 has several programming projects, including a project that uses heaps. p p This presentation shows you what a heap is, and demonstrates.
CPS 100, Fall PFTN2Wks l Making progress on Boggle assignment  Many, many classes, each designed to do one thing  Some related by inheritance,
CPS 100, Fall GridGame APT How would you solve this problem using recursion?
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
CompSci 100E 39.1 Memory Model  For this course: Assume Uniform Access Time  All elements in an array accessible with same time cost  Reality is somewhat.
CompSci 100E 24.1 Data Compression  Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant factor.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
CPS Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze  Certain mazes can be solved using the “right-hand”
CPS Heaps, Priority Queues, Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant.
CompSci 100e 6.1 Plan for the week l More recursion examples l Backtracking  Exhaustive incremental search  When we a potential solution is invalid,
CS 361 – Chapter 5 Priority Queue ADT Heap data structure –Properties –Internal representation –Insertion –Deletion.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
CompSci 100 Prog Design and Analysis II Oct 26, 2010 Prof. Rodger CPS 100, Fall
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
CSE 373: Data Structures and Algorithms Lecture 11: Priority Queues (Heaps) 1.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
1. What is it? It is a queue that access elements according to their importance value. Eg. A person with broken back should be treated before a person.
CPS Heaps, Priority Queues, Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  Why is compression important?
CompSci Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze ä Certain mazes can be solved using the.
CPS Backtracking, Search, Heuristics l Many problems require an approach similar to solving a maze ä Certain mazes can be solved using the “right-hand”
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
1 CSC 421: Algorithm Design Analysis Spring 2013 Transform & conquer  transform-and-conquer approach  presorting  balanced search trees, heaps  Horner's.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
CPS 100, Spring Search, Trees, Games, Backtracking l Trees help with search  Set, map: binary search tree, balanced and otherwise  Quadtree.
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.
TWTG What work is still to come APT, Huff, APT
Game playing Types of games Deterministic vs. chance
TWTG What work is still to come APT, Huff, APT
Backtracking, Search, Heuristics
Data Compression Compression is a high-profile application
Hashing Exercises.
Compsci 201 Priority Queues & Autocomplete
Heaps, Priority Queues, Compression
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
i206: Lecture 14: Heaps, Graphs intro.
Heaps Chapter 11 has several programming projects, including a project that uses heaps. This presentation shows you what a heap is, and demonstrates.
Data Structures and Analysis (COMP 410)
Priority Queues CSE 373 Data Structures.
Priority Queues & Heaps
CO4301 – Advanced Games Development Week 4 Binary Search Trees
B-Trees.
Compsci 201 Priority Queues + Heaps Autocomplete
Data Structures for Shaping and Scheduling
Scoreboard What else might we want to do with a data structure?
Backtracking, Search, Heuristics
Backtracking, Search, Heuristics
Presentation transcript:

CPS 100e, Spring Day, Week, Month Overview l Backtracking p/review  Boggle  APT l Assignment review  Boggle  APT l PQ Overview

CPS 100e, Spring Backtracking by image search

CPS 100e, Spring Searching with no guarantees l Search for best move in automated game play  Can we explore every move?  Are there candidate moves ranked by “goodness”?  Can we explore entire tree of possible moves? l Search with partial information  Predictive texting with T9 or iTap or …  Finding words on a Boggle board  What numbers fit in Sudoku suare l Try something, if at first you don’t succeed ….

CPS 100e, Spring Search, Backtracking,Heuristics l How do you find a needle in a haystack?  How does a computer play chess?  Why would you write that program?  l How does Bing/Googlemap find routes from one place to another?  Shortest path algorithms  Longest path algorithms l Optimal algorithms and heuristic algorithms  When is close good enough? How do measure “closeness”?  When is optimality important, how much does it cost?

CPS 100e, Spring Exhaustive Search/Heuristics l We use binary search trees to organize data, in searching we don’t need to examine all the data to find what we’re looking for  Where is the smallest item in a search tree? Largest?  How are trees balanced? l What do we do when the search space is huge?  How many chess boards are there?  Count routes between my house and yours? l Exhaustive search: look at everything!

CPS 100e, Spring 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  Horiz/Vert/Diag attacks l Backtracking  Tentative placement  Recurse, if ok done!  If fail, undo tentative, retry l wikipedia-n-queens wikipedia-n-queens

CPS 100e, Spring Backtracking idea with N queens l For each column C, tentatively place a queen  Try first row in column C, if ok, move onto next column Typically “move on” is recursive  If solved, done, otherwise try next row in column C Must unplace queen when failing/unwind recursion l Each column C “knows” what row R it’s on  If first time, that’s row zero, but might be an attack  Unwind recursion/backtrack, try “next” location l Backtracking: record an attempt go forward  Move must be “undoable” on backtracking/unwinding

CPS 100e, Spring N queens backtracking: Queens.java public boolean solve(int col){ if (col == mySize) return true; // try each row until all are tried for(int r=0; r < mySize; r++){ if (myBoard.safeToPlace(r,col)){ myBoard.setQueen(r,col,true); if (solve(col+1)){ return true; } myBoard.setQueen(r,col,false); } return false; }

CPS 100e, Spring Basic ideas in backtracking search l 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 Backtracking step, choices must be undoable l Inherently recursive, when to stop searching?  When all columns tried in N queens  When we have found the exit in a maze  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

CPS 100e, Spring Pruning vs. Exhaustive Search l If we consider every possible placement of 4 queens on a 4x4 board, how many are there? (N queens)  4x4x4x4 if we don’t pay attention to any attacks  4x3x2x1 if we avoid attacks in same row l What about if we avoid diagonal attacks?  Pruning search space makes more search possible, still could be lots of searching to do! l Estimate how long to calculate # solutions to the N- queens problem with our Java code….

CPS 100e, Spring Daphne Koller l 2004, Macarthur l 2008, first ACM/Infosys l “The world is noisy and messy …You need to deal with the noise and uncertainty.” “I find it distressing that the view of the field is that you sit in your office by yourself surrounded by old pizza boxes and cans of Coke, hacking away at the bowels of the Windows operating system,” she said. “I spend most of my time thinking about things like how does a cell work or how do we understand images in the world around us?”

CPS 100e, Spring 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?

CPS 100e, Spring Games at Duke l Alan Biermann  Natural language processing  Compsci 1: Great Ideas  Duchess, checkers, chess l Tom Truscott  Duke undergraduate working with/for Biermann  Usenet: online community l Second EFF Pioneer Award (with Vint Cerf!) Second EFF Pioneer Award (with Vint Cerf!)

CPS 100e, Spring Heuristics l A heuristic is a rule of thumb, doesn’t always work, isn’t guaranteed to work, but useful in many/most cases  Search problems that are “big” often can be approximated or solved with the right heuristics l What heuristic is good for Sudoku?  Is there always a no-reasoning move, e.g., 5 goes here?  What about “if I put a 5 here, then…”  Do something else? l What other optimizations/improvements can we make?  For chess, checkers: good heuristics, good data structures

CPS 100e, Spring Boggle Program

CPS 100e, Spring OO Aside: Interfaces, Abstract Classes l Interface is a contract  X implements Y provides method implementations  No code sharing among implementing classes  Characteristics of interface: signatures only  Why create an interface? l Abstract class leverages common code  Often implements interface with common code  Consider Map/AbstractMap, List/AbstractList,…  One method labeled abstract, requires implementation!

CPS 100e, Spring Interfaces and Abstraction in Boggle General idea: create IThing for interfaces  IPlayer, IAutoPlayer, ILexicon, IBoardMaker  Facilitates new implementations if Ixx fixed Changing the interface creates cascade of changes l AbstractPlayer and AbstractAutoPlayer  Factor out common code, differentiate in subclasses  Facilitate play by Controller/View, back-and-forth plays  Be careful, be wary of ignoring/not knowing parent code How do you update score in an BoardFirstAutoPlayer? l How can you create different boards?

CPS 100e, Spring YAQ, YAQ, haha! (Yet Another Queue) l What is the dequeue policy for a Queue?  Why do we implement Queue with LinkedList Interface and class in java.util  Can we remove an element other than first? l How does queue help word-ladder/shortest path?  First item enqueued/added is the one we want  What if different element is “best”? l PriorityQueue has a different dequeue policy  Best item is dequeued, queue manages itself to ensure operations are efficient

CPS 100e, Spring PriorityQueue raison d’être l Algorithms Using PQ for efficiency  Shortest Path: Mapquest/Garmin to Internet Routing How is this like word-ladder? How different?  Event based simulation Coping with explosion in number of particles or things  Optimal A* search, game-playing, AI, Can’t explore entire search space, can estimate good move l Data compression facilitated by priority queue  Alltime best assignment in a Compsci 100/100e course? Subject to debate, of course  From A-Z, soup-to-nuts, bits to abstractions

CPS 100e, Spring PQ Application: Data Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant factor in what made Napster work (why did Napster ultimately fail?)  Who invented Napster, how old, when? l Why do we care?  Secondary storage capacity doubles every year  Disk space fills up quickly on every computer system  More data to compress than ever before  Will we ever need to stop worrying about storage?

CPS 100e, Spring More on Compression l Different compression techniques .mp3 files and.zip files? .gif and.jpg?  Lossless and lossy l Impossible to compress/lossless everything: Why? l Lossy methods  Good for pictures, video, and audio (JPEG, MPEG, etc.) l Lossless methods  Run-length encoding, Huffman, LZW, … 

CPS 100e, Spring Priority Queue l Compression motivates ADT priority queue  Supports two basic operations add/insert -– an element into the priority queue remove/delete – the minimal element from the priority queue  Implementations allow getmin/peek as well as delete Analogous to top/pop, peek/dequeue in stacks, queues l Think about implementing the ADT, choices?  Add compared to min/remove  Balanced search tree is ok, but can we do better?

CPS 100e, Spring Priority Queue sorting l See PQDemo.java,  code below sorts, complexity? String[] array = {...}; // array filled with data PriorityQueue pq = new PriorityQueue (); for(String s : array) pq.add(s); for(int k=0; k < array.length; k++){ array[k] = pq.remove(); } l Bottlenecks, operations in code above  Add words one-at-a-time to PQ v. all-at-once  What if PQ is an array, add or remove fast/slow?  We’d like PQ to have tree characteristics, why?

CPS 100e, Spring Priority Queue top-M sorting l What if we have lots and lots and lots of data  code below sorts top-M elements, complexity? Scanner s = … // initialize; PriorityQueue pq = new PriorityQueue (); while (s.hasNext()) { pq.add(s.next()); if (pq.size() > M) pq.remove(); } l What’s advantageous about this code?  Store everything and sort everything?  Store everything, sort first M?  What is complexity of sort: O(n log n)

CPS 100e, Spring Priority Queue implementations l Priority queues: average and worst case Insert average Getmin (delete) Insert worst Getmin (delete) Unsorted list Sorted list Search tree Balanced tree Heap log n O(n) O(1)log n O(n)O(1)O(n)O(1) O(n)O(1)O(n)O(1) l Heap has O(n) build heap from n elements

CPS 100e, Spring PriorityQueue.java (Java 5+) l What about objects inserted into pq?  Comparable, e.g., essentially sortable  How can we change what minimal means?  Implementation uses heap, tree stored in an array l Use a Comparator for comparing entries we can make a min-heap act like a max-heap, see PQDemo  Where is class Comparator declaration? How used?  What if we didn't know about Collections.reverseOrder? How do we make this ourselves?

CPS 100e, Spring Big-Oh and a tighter look at inserts l log(1) + log(2) + log(3) + … + log(n)  Property of logs, log(a) + log(b) = log(a*b)  log(1*2*3*…*n) = log(n!) l We can show using Sterling’s formula: l log(n!) = c 1 *log(n) + nlog(n) – c 2 *n l We can get O(n log n) easily, this goes tight, lower,  n log n) as well

CPS 100e, Spring Priority Queue implementation l Heap data structure is fast and reasonably simple  Why not use inheritance hierarchy as was used with Map?  Trade-offs when using HashMap and TreeMap: Time, space, ordering properties, TreeMap support? l Changing comparison when calculating priority?  Create object to replace, or in lieu of compareTo Comparable interface compares this to passed object Comparator interface compares two passed objects  Both comparison methods: compareTo() and compare() Compare two objects (parameters or self and parameter) Returns –1, 0, +1 depending on

CPS 100e, Spring Creating Heaps l Heap: array-based implementation of binary tree used for implementing priority queues:  add/insert, peek/getmin, remove/deletemin, O(???) l Array minimizes storage (no explicit pointers), faster too, contiguous (cache) and indexing l Heap has shape property and heap/value property  shape: tree filled at all levels (except perhaps last) and filled left-to-right (complete binary tree)  each node has value smaller than both children

CPS 100e, Spring Array-based heap l store “node values” in array beginning at index 1 l for node with index k  left child: index 2*k  right child: index 2*k+1 l why is this conducive for maintaining heap shape? l what about heap property? l is the heap a search tree? l where is minimal node? l where are nodes added? deleted?

CPS 100e, Spring Thinking about heaps Where is minimal element?  Root, why? l Where is maximal element?  Leaves, why? l How many leaves are there in an N-node heap (big-Oh)?  O(n), but exact? l What is complexity of find max in a minheap? Why?  O(n), but ½ N? l Where is second smallest element? Why?  Near root?

CPS 100e, Spring Adding values to heap l to maintain heap shape, must add new value in left-to-right order of last level  could violate heap property  move value “up” if too small l change places with parent if heap property violated  stop when parent is smaller  stop when root is reached l pull parent down, swapping isn’t necessary (optimization) insert 8 bubble 8 up

CPS 100e, Spring Adding values, details (pseudocode) void add(Object elt) { // add elt to heap in myList myList.add(elt); int loc = myList.size()-1; while (1 < loc && elt < myList.get(loc/2)){ myList.set(loc,myList.get(loc/2)); loc = loc/2; // go to parent } // what’s true here? myList.set(loc,elt); } array myList

CPS 100e, Spring Removing minimal element l Where is minimal element?  If we remove it, what changes, shape/property? l How can we maintain shape?  “last” element moves to root  What property is violated? l After moving last element, subtrees of root are heaps, why?  Move root down (pull child up) does it matter where? l When can we stop “re- heaping”?  Less than both children  Reach a leaf

CPS 100e, Spring Anita Borg “Dr. Anita Borg tenaciously envisioned and set about to change the world for women and for technology. … she fought tirelessly for the development technology with positive social and human impact.” l “Anita Borg sought to revolutionize the world and the way we think about technology and its impact on our lives.” l ch?v=1yPxd5jqz_Q ch?v=1yPxd5jqz_Q