CS 410 Applied Algorithms Applied Algorithms Lecture # Backtracking.

Slides:



Advertisements
Similar presentations
CS 410 Applied Algorithms Applied Algorithms Lecture #7 Counting.
Advertisements

CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
 Given a matrix of size N x N and some operations of rotation or reflection, determine the final state of the matrix.  The operations can be: ◦ Rotate.
BackTracking Algorithms
Greed is good. (Some of the time)
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Designing Algorithms Csci 107 Lecture 4. Outline Last time Computing 1+2+…+n Adding 2 n-digit numbers Today: More algorithms Sequential search Variations.
Divide and Conquer. Recall Complexity Analysis – Comparison of algorithm – Big O Simplification From source code – Recursive.
Nattee Niparnan. Recall  Complexity Analysis  Comparison of Two Algos  Big O  Simplification  From source code  Recursive.
Computer Science 1620 Loops.
CS 410 Applied Algorithms Applied Algorithms Lecture #3 Data Structures.
Cs536 Functional Programming 16/13/2015 Lecture #2.5 Today’s Topics A Few Less Trivial Examples – Numerical Functions »Differentiation and square root.
Efficiency of Algorithms
Monday, 12/9/02, Slide #1 CS 106 Intro to CS 1 Monday, 12/9/02  QUESTIONS??  On HW #5 (Due 5 pm today)  Today:  Recursive functions  Reading: Chapter.
Designing Algorithms February 2nd. Administrativia Lab assignments will be due every Monday Lab access –Searles 128: daily until 4pm unless class in progress.
CS 410 Applied Algorithms Applied Algorithms Lecture #10 Graph Traversal.
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
Chapter 1 pp 1-14 Properties of Algorithms Pseudocode.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Designing Algorithms Csci 107 Lecture 4.
Algorithm Efficiency and Sorting
CS 410 Applied Algorithms Applied Algorithms Lecture #5 Sorting.
CS 410 Applied Algorithms Applied Algorithms Lecture #6 Arithmetic and Algebra.
CS 206 Introduction to Computer Science II 10 / 08 / 2008 Instructor: Michael Eckmann.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Backtracking.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
HOW TO SOLVE IT? Algorithms. An Algorithm An algorithm is any well-defined (computational) procedure that takes some value, or set of values, as input.
COMP Introduction to Programming Yi Hong May 13, 2015.
CS 2430 Day 28. Announcements We will have class in ULR 111 on Monday Exam 2 next Friday (sample exam will be distributed next week)
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.
Nattee Niparnan. Recall  Complexity Analysis  Comparison of Two Algos  Big O  Simplification  From source code  Recursive.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
Fundamentals of Algorithms MCS - 2 Lecture # 7
Jessie Zhao Course page: 1.
CS 241 – Computer Programming II Lab Kalpa Gunaratna –
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
COMP Recursion, Searching, and Selection Yi Hong June 12, 2015.
By the end of this session you should be able to...
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
CSIS 113A Lecture 5 Random Numbers, while, do-while.
Word problems DON’T PANIC! Some students believe they can’t do word problem solving in math. Don’t panic. It helps to read the question more than once.
1 Section 2.1 Algorithms. 2 Algorithm A finite set of precise instructions for performing a computation or for solving a problem.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 3: Levels of Abstraction
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
David Evans Class 15: P vs. NP (Smiley Puzzles and Curing Cancer) CS150: Computer Science University of Virginia Computer.
CS216: Program and Data Representation University of Virginia Computer Science Spring 2006 David Evans Lecture 8: Crash Course in Computational Complexity.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
CISC105 – General Computer Science Class 4 – 06/14/2006.
CSCI 125 & 161 Lecture 12 Martin van Bommel. Prime Numbers Prime number is one whose only divisors are the number 1 and itself Therefore, number is prime.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
David Evans CS200: Computer Science University of Virginia Computer Science Lecture 14: P = NP?
1 Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function Definition float sqrt(float x) { // compute.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Lesson Objectives Aims Understand the following “standard algorithms”:
Algorithm Analysis CSE 2011 Winter September 2018.
CS 213: Data Structures and Algorithms
Recursion (Continued)
Recursion (Continued)
Building Java Programs
Recursion (Continued)
Building Java Programs
Presentation transcript:

CS 410 Applied Algorithms Applied Algorithms Lecture # Backtracking

CS 410 Applied Algorithms Announcements ACM Student Chapter Meeting –Where: FAB-150. Fourth Avenue Building, across the hallway from the Linux Lab – When: Wednesday, June 1. 11:30AM – Topic: Become an Undergrad Researcher at PSU! Final Exam Date –Monday, June 6, 2005 –12:30 – 14:20 PM

CS 410 Applied Algorithms Checking for primality Bool prime(int n) // test for primality of n { int i; int m; if (n==2) return TRUE; if (n<2) return FALSE; m = sqrt(n)+1; for (i=2;i<=m;i++) if (n%i == 0) return FALSE; return TRUE; }

CS 410 Applied Algorithms Sum of 4 primes Why won’t this work? for (i=2, i<=n, i++) if (prime(i)) for (j=2, j<=n, j++) if (prime(j)) for (k=2, k<=n, k++) if (prime(k)) for (l=2, l<=n, l++) if (prime(l)) if (i+j+k+l=target) printf(“%ld %ld %ld %ld\n”,I,j,k,l)

CS 410 Applied Algorithms What if we looped over just primes Precompute all the primes from 1 to target Int primes[size] Void initPrimes(int largest) { …} How many primes are there between 1 and 10,000,000 ?

CS 410 Applied Algorithms Lets explore? int countPrimes(int n) { int i; int count; count = 0; for (i=2;i<=n;i++) { if (prime(i)) count++; if (i% == 0) printf("i= %ld, num primes= %ld\n",i,count); } printf("num primes= %ld density= %ld\n",count,n/count); }

CS 410 Applied Algorithms Analyze Are there a lot of primes? What’s the average distance between primes? Is this number big? Does this suggest a solution?

CS 410 Applied Algorithms Largest distance between primes int enumerate(int n) { int i; int count; int last; int maxdif; count = 0; last = 2; maxdif = 0; for (i=3;i<=n;i++) { if (prime(i)) { count++; maxdif = max(i-last,maxdif); last = i;}; if (i% == 0) printf("i= %ld, num primes= %ld, maxdif= %ld\n“,i,count,maxdif); }

CS 410 Applied Algorithms Can we find 3 primes? Why is this more feasible? Should be easy to find 3 primes that add up to a small integer since we need only loop through primes up to that integer. If max=154, how many small primes will we need?

CS 410 Applied Algorithms int firstThirty() { int i; int count; count = 0; for (i=2;count<30;i++) if (prime(i)) { count++; printf("%ld,",i);}; }

CS 410 Applied Algorithms Strategy /* An array of the first 30 small primes */ int sp[30] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113}; int ps[200][3]; /* ps[6] = {2,2,2} ps[i] stores 3 primes that add up to i ps[7] = {2,2,3} ps[8] = {2,3,3}... ps[199]= {3,83,113} */

CS 410 Applied Algorithms Computing ps int init_ps_sub(n) { int j; int k; int l; for (j=0;j<30;j++) // Find 3 small primes for (k=0;k<30;k++) // such that p1+p2+p3 = n for (l=0;l<30;l++) // store them in the "ps" array if (sp[j]+sp[k]+sp[l]==n) { ps[n][0] = sp[j]; ps[n][1] = sp[k]; ps[n][2] = sp[l]; return 0;}; printf("Can't find 3 small primes for %ld\n",n); }

CS 410 Applied Algorithms Computing 4 primes int test(int n) { int i; int diff; if (n<8) { printf("Imposible\n"); return 0; } for (i=n-6; i>=2; i--) // find largest prime at least if (prime(i)) // 6 less than n, call it "i" { diff = n-i; // then lookup 3 small primes printf("%ld %ld %ld %ld\n“,i,ps[diff][0],ps[diff][1],ps[diff][2]); return 0; } }

CS 410 Applied Algorithms In Class Problems Queue –Page 179 of the text –We will discuss this in class

CS 410 Applied Algorithms Queues of N people of different height How can we count how many can see to the left? To the right?

CS 410 Applied Algorithms Problem Given a queue of fixed size N. A fixed number of people who can see to the left. A fixed number of people who can see to the right. How many way can we arrange the N people to get the matching left and right counts?

CS 410 Applied Algorithms Solution? Compute all possible ways to arrange N people. Throw away those that don’t have the correct left and right count. Arranging things in different order is called a permutation.

CS 410 Applied Algorithms Computing permutations What are the permutations of [1,2,3] ? Chose an element. –Choices are 1, 2, or 3 –For each choice prepend it to the permutations of what’s left after removing the choice. Candidates [1,2,3] – (1,[2,3]) (2,[1,3]) (3,[1,2]) –What are the permutations of [2,3]? [2,3] and [3,2]

CS 410 Applied Algorithms Permutations [1,2,3] = candidates = (1,[2,3]) (2,[1,3])(3,[1,2]) permutations [2,3] = [2,3], [3,2] [1,3] = [1,3],[3,1] [1,2] = [1,2],[2,1] [1,2,3] [1,3,2] [2,1,3],[2,3,1] [3,1,2],[3,2,1]

CS 410 Applied Algorithms candidates xs = f [] xs where f before (choice:after) = (choice,reverse before++after) : (f (choice:before) after) f before [] = [] gen2 :: [Int] -> [Int] -> [[Int]] -> [[Int]] gen2 chosen [] all = (reverse chosen):all gen2 chosen toAdd all = add pairs all where pairs = candidates toAdd add [] all = all add ((choice,remains):pairs) all = add pairs (gen2 (choice:chosen) remains all)

CS 410 Applied Algorithms How many permutations are there? [1,2,3,4] 4 choices For each choice we prepend it to the permutations of list of size three. Perms([ ] 0 ) = 1 (the empty sequence) Perms([ ] x+1 ) = (x+1) * Perms([ ] x ) Perms([ ] n ) = n!

CS 410 Applied Algorithms We need some trick Find the tallest person, and then break it into 2 sub problems. Where can the tallest person be given left and right numbers?

CS 410 Applied Algorithms Bounding the tallest If left = n, then tallest must be at position at least n, If right = m, then tallest must be at position at most Max- m+1 So tallest must be between Left  tallest  N-Right+1 Left=3 Right=3

CS 410 Applied Algorithms Solving the sub problem k = exact number of views to the left required n = size of the permutation required chosen is the prefix of the permutation so far remains = the set left to choose the next element from p2 k n chosen remains all | length chosen == n = (reverse chosen,remains):all | True = add pairs all where pairs = candidates remains add [] all = all add ((x,rs):pairs) all = let next = (x:chosen) in if (possible k n next) then (p2 k n next rs (add pairs all)) else (add pairs all)

CS 410 Applied Algorithms What’s possible? Sometimes we know a chosen sequence can’t lead to a good solution. possible k n xs = viewl <= k && viewl + n - len >= k where len = length xs viewl = countRight xs

CS 410 Applied Algorithms All possible winners try2 n left right | n+1 < left+right = [] | True = concat (map each positionsN) where positionsN = [left.. n - right + 1] each i = concat(map f leftChoices) where leftChoices = p2 (left-1) (i-1) [] [1..n-1] [] f (lefts,remains) = concat(map add (p2 (right-1) (n-i) [] remains [])) where add (rights,_) = [lefts ++ [n] ++ reverse rights]

CS 410 Applied Algorithms Today’s Assignments Read for next time Chapter 9 of the text. pp Be prepared to answer questions in class next Friday from the reading. Programming assignment Bigger Square Please Page 186 Write a solution Submit your solution (until you get it right) Hand in both your program, and the judge output. Those who volunteer to discuss their program get class participation points. me solutions before noon on Friday, May 6.