Applied Algorithms

27
CS 410 Applied Algorithms Applied Algorithms Lecture # Backtracking

description

Applied Algorithms. Lecture # Backtracking. 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 - PowerPoint PPT Presentation

Transcript of Applied Algorithms

Page 1: Applied Algorithms

CS 410 Applied Algorithms

Applied Algorithms

Lecture #Backtracking

Page 2: Applied Algorithms

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

Page 3: Applied Algorithms

CS 410 Applied Algorithms

Checking for primalityBool 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;}

Page 4: Applied Algorithms

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)

Page 5: Applied Algorithms

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 ?

Page 6: Applied Algorithms

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%100000 == 0) printf("i= %ld, num primes= %ld\n",i,count); } printf("num primes= %ld density= %ld\n",count,n/count);}

Page 7: Applied Algorithms

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?

Page 8: Applied Algorithms

CS 410 Applied Algorithms

Largest distance between primesint 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%100000 == 0) printf("i= %ld, num primes= %ld, maxdif= %ld\n“ ,i,count,maxdif);}}

Page 9: Applied Algorithms

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?

Page 10: Applied Algorithms

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);};}

Page 11: Applied Algorithms

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}*/

Page 12: Applied Algorithms

CS 410 Applied Algorithms

Computing psint 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);}

Page 13: Applied Algorithms

CS 410 Applied Algorithms

Computing 4 primesint 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; }}

Page 14: Applied Algorithms

CS 410 Applied Algorithms

In Class Problems

• Queue 8.6.3– Page 179 of the text– We will discuss this in class

Page 15: Applied Algorithms

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?

Page 16: Applied Algorithms

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?

Page 17: Applied Algorithms

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.

Page 18: Applied Algorithms

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]

Page 19: Applied Algorithms

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]

Page 20: Applied Algorithms

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):allgen2 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)

Page 21: Applied Algorithms

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!

Page 22: Applied Algorithms

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?

Page 23: Applied Algorithms

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=3Right=3

Page 24: Applied Algorithms

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)

Page 25: Applied Algorithms

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

Page 26: Applied Algorithms

CS 410 Applied Algorithms

All possible winnerstry2 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]

Page 27: Applied Algorithms

CS 410 Applied Algorithms

Today’s AssignmentsRead for next time

Chapter 9 of the text. pp 188-218 Be prepared to answer questions in class next Friday from the

reading.

Programming assignment• 8.6.8 Bigger Square Please• Page 186• Write a solutionSubmit 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.

Email me solutions before noon on Friday, May 6.