Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 1 - - PowerPoint PPT Presentation

compsci 201 201 more sorti ting b backtra ktracking par
SMART_READER_LITE
LIVE PREVIEW

Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 1 - - PowerPoint PPT Presentation

Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 1 1 of of 4 Susan Rodger April 3, 2020 4/3/2020 Compsci 201, Spring 2020 1 T is for Alan Turing, Turing Test, Turing award From WWII to philosophy to math to


slide-1
SLIDE 1

Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 1 1 of

  • f 4

4/3/2020 Compsci 201, Spring 2020 1

Susan Rodger April 3, 2020

slide-2
SLIDE 2

T is for …

  • Alan Turing, Turing Test, Turing award
  • From WWII to philosophy to math to computing
  • Tree
  • From Search to Game to …

4/3/2020 Compsci 201, Spring 2020 2

slide-3
SLIDE 3

Announcements

  • APT

PT-6 due T Tuesd sday, A Apri ril 7

  • Assig

ignme ment P t P5 Percola latio tion

  • Tell us solo or partner form due yesterday
  • Code due Thursday, April 9
  • Disc

scuss ssion 11 Monday, A Apri ril 6 6

  • Pre-discussion coming soon
  • Exam 2 i

is A s Apri ril 10

  • Online, flexible hours, extra time, open notes
  • Your own work
  • APT Q

Quiz iz 2 2 is April 1 il 11-15 15

  • Your own work

4/1/2020 Compsci 201, Spring 2020 3

slide-4
SLIDE 4

If you need an extension for work

  • Fill

ill o

  • ut

ut t the f he form o

  • n

n the c he cour urse w web eb page, und under fo forms ms t tab

  • Then t

n take t the e e extens ensio ion

  • If you

u need need m more t e tim ime, t tak ake it it again

  • Try no

not t to get t too far ar b behin ehind!

4/3/2020 Compsci 201, Spring 2020 4

slide-5
SLIDE 5

PfFFiA

  • Finis

ish/R h/Revie iew s sorting ing

  • Loop invariants with efficient and inefficient

sorts

  • How a priority queue works
  • Bubblesort focus, Oh No!
  • Backtr

ktracki king: NQuee eens ns and and m more

  • Canonical problem-solving and programming

4/3/2020 Compsci 201, Spring 2020 5

slide-6
SLIDE 6

Simple, O(n2) sorts

  • Selectio

tion s sort t --- n2 compa mparis isons, n n swaps ps

  • Find min, swap to front, increment front, repeat
  • In

Inse sertion sor sort --- n2 com

  • mpariso

sons, n no

  • sw

swap, sh shift

  • stable

ble, fast on sorted data, slide into place

  • Bubble

bble s sort --- n2 ever erythi hing ng, s slow*

  • Catchy name, but slow and ugly*

*this isn't everyone's opinion, but it should be

  • Shell s

ll sort: q : quasi-in insertio tion, f fast i in practi tice

  • Not quadratic with some tweaks

4/3/2020 Compsci 201, Spring 2020 6

slide-7
SLIDE 7

Case Study: SelectionSort

  • Cano

nonical O nical O(n2) a algorit ithm hm/co /code e

4/3/2020 Compsci 201, Spring 2020 7

slide-8
SLIDE 8

Case Study: SelectionSort

  • Invar

ariant iant: o : on jth

th pass, [0,j) is

is in in final inal s sorted o

  • rder

er

  • Nested loop re-establishes invariant

4/3/2020 Compsci 201, Spring 2020 8

public void sort(List<T> list) { for(int j=0; j < list.size()-1; j++) { int min = j; for(int k=j+1; k < list.size(); k++) { if (list.get(k).compareTo(list.get(min)) < 0){ min = k; } } swap(list,min,j); } } Final order unexamined j

slide-9
SLIDE 9

Reminder: Loop Invariant

  • Statement

ent: t : true e ue each t ch time l loop begins ins t to execut cute

  • During loop execution it may become false
  • The loop re-establishes the invariant
  • Typically stated in terms of loop index
  • Pictures can help reason about code/solution
  • Help

elps t to rea eason f formally and and inf informally ab about the he code e you’re w e writing ing

  • Can I explain the invariant to someone?

4/3/2020 Compsci 201, Spring 2020 9

slide-10
SLIDE 10

Bubblesort isn't much code

  • Swap

ap ad adjacent elem elements w when hen o

  • ut

ut o

  • f order
  • From beginning to end, then end-1, end-2, …
  • After

er n n passes es, las ast n n-ele element nts i in place ce

4/3/2020 Compsci 201, Spring 2020 10

slide-11
SLIDE 11

Timing of n2 and other sorts

4/3/2020 Compsci 201, Spring 2020 11

slide-12
SLIDE 12

More efficient O(n log n) sorts

  • Div

ivid ide and and co conq nquer s sorts:

  • Quick s

k sort: fast in practice, O(n2) worst case

  • Merg

rge s sort: stable, fast, extra storage

  • Timsort: http://en.wikipedia.org/wiki/Timsort
  • Other s

sor

  • rts:
  • Heap sort: priority queue sorting
  • Radix sort: uses digits/characters (no

compare)

  • O(n l

log n) is o

  • ptimal f

al for c comparing ing

  • But, Radix is O(n) ??

4/3/2020 Compsci 201, Spring 2020 12

slide-13
SLIDE 13

Stable, Stability

  • Stab

able le: r : respec ect o

  • rder

er o

  • f equal k

l keys when s sorting ing

  • First sort by shape, then by color: Stable!
  • Triangle < Square < Circle; Yellow < Green < Red

4/3/2020 Compsci 201, Spring 2020 13

slide-14
SLIDE 14

Merge Sort

  • Idea: Divide and Conquer
  • Divide list into two halves
  • Sort both halves (smaller problem)
  • Merge the two sorted halves

9 5 1 4 3 6 2 7

Compsci 201, Spring 2020 14 4/3/2020

slide-15
SLIDE 15

What does recursively sort mean? Merge Sort

  • Use the same Merge Sort algorithm

– Divide list into two halves – Sort both halves (smaller problem) – Merge the two sorted halves 9 5 1 4 9 5 1 4 divide list into 2 halves 5 9 1 4 recursively sort each half 1 4 5 9 merge the two sorted list

16 Compsci 201, Spring 2020 4/3/2020

slide-16
SLIDE 16

Merge two sorted lists

  • Both lists are sorted.

1 4 5 9 2 3 6 7 Find the smallest from front of two lists

18 Compsci 201, Spring 2020 4/3/2020

slide-17
SLIDE 17

MergeSort idea for code

mergesort(data) n = length of data if n is 1: return data else: d1 = mergesort(first half of data) d2 = mergesort(second half of data) return merge(d1, d2)

27 4/3/2020 Compsci 201, Spring 2020

slide-18
SLIDE 18

Time for MergeSort n items: T(n)

mergesort(data) n = length of data if n is 1: return data else: d1 = mergesort(first half of data) d2 = mergesort(second half of data) return merge(d1, d2)

28 4/3/2020 Compsci 201, Spring 2020

slide-19
SLIDE 19

Quicksort - Idea

  • Pivot – select and adjust < pivot, pivot, > pivot

– Select one of the elements – Put it where it belongs in sorted order – Put elements less than it, to its left – Put elements greater than it, to its right

  • Recursively sort the elements to its left
  • Recursively sort the elements to its right

Compsci 201, Spring 2020 30 4/3/2020

slide-20
SLIDE 20

Quicksort - Idea

  • Pivot – select and adjust < pivot, pivot, > pivot
  • Recursively sort the elements to its left
  • Recursively sort the elements to its right

5 9 1 4 3 6 2 7

Compsci 201, Spring 2020 31 4/3/2020

slide-21
SLIDE 21

Quicksort: fast in practice

  • Inv

nvented in in 1962 b 1962 by Tony ny H Hoar are, d did idn' n't und under erstand recur cursio ion: n:

  • Canonical T(n) = 2T(n/2)+O(n), but
  • Worst case is O(n2), bad pivot. Shuffle first?

<= X > X X

pivot index

4/3/2020 Compsci 201, Spring 2020 33

void doQuick(List<T> list, int first, int last) { if (first >= last) return; int piv = pivot(list,first,last); doQuick(list,first,piv-1); doQuick(list,piv+1,last); }

slide-22
SLIDE 22

Pivot is O(n)

  • Invar

ariant iant: : [first,p] <= list.get(first)

  • Invar

ariant iant: : (p,k) > list.get(first)

<= X > X X

pivot index

4/3/2020 Compsci 201, Spring 2020 34

private int pivot(List<T> list, int first, int last){ T piv = list.get(first); int p = first; for(int k=first+1; k <= last; k++){ if (list.get(k).compareTo(piv) <= 0){ p++; swap(list,k,p); } } swap(list,p,first); return p; }

<= [first]

??? k first

> [first]

p

slide-23
SLIDE 23

https://en.wikipedia.org/wiki/Timsort

  • Stable, O

O(n n lo log n) n) in in average and and w worst, O O(n) n) b bes est!

  • In practice lots of data is "close" to sorted
  • Invent

ented by Tim P Peter ers for P Pytho hon, n, now i in J Java

  • Replaced merge sort which is also stable
  • Engineer

ineered ed t to be correct ect, f , fas ast, u useful i ul in pract ctic ice

  • Theory and explanation not so simple

https://www.youtube.com/watch?v=NVIjHj-lrT4

4/3/2020 Compsci 201, Spring 2020 35

slide-24
SLIDE 24

Summary of O(n log n) sorts

  • Ti

Timsort: hy hybrid o

  • f mer

erge and and ins insertion?

  • Fast in real world: Python, Java 7+, Android
  • Wha

hat’s the b he bes est O O(n lo n log n) n) sort t to call all?

  • The one in the library you have access to
  • Arrays.sort or Collections.sort
  • Chang

anging ing how y you s sort: :

  • .compareTo() or .compare()

4/3/2020 Compsci 201, Spring 2020 36

slide-25
SLIDE 25

sortingwoto or ginooorsttw

  • http://b

//bit it.l .ly/2 /201sprin ing20-04 0403 03-1

4/3/2020 Compsci 201, Spring 2020 37

slide-26
SLIDE 26

Brian Fox

GNU Bash Shell (developer) First employee at Free Software Foundation First online banking system at Wells Fargo

There’s nothing that I am better at than everyone else, except being me. There’s no secret to being me. Follow your interests and work hard at them. Then you will play bass better, program better, cook better, ride motorcycles better, or anything else that you really want to do.

4/3/2020 Compsci 201, Spring 2020 38

https://lifehacker.com/im-brian-fox-author-of-the-bash-shell-and-this-is-how-1820510600

slide-27
SLIDE 27

Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 2 2 of

  • f 4

4/3/2020 Compsci 201, Spring 2020 39

Susan Rodger April 3, 2020

slide-28
SLIDE 28

How does a Priority Queue work?

  • Imple

lemented w wit ith a h a Heap eap

  • Tree that is stored in an array.
  • It is NOT a tree
  • But easier to think of it as a tree
  • It REALLY is an array

4/3/2020 Compsci 201, Spring 2020 40

slide-29
SLIDE 29

How does a priority queue work?

  • Imple

lementation w wit ith a h a heap heap

  • Tree that is stored in an array
  • Min heap, remove always returns the min
  • Could make it a max heap
  • Use comparator to change
  • Root is in index 1
  • Left child: index 2*k
  • Right child: index 2*k + 1

4/3/2020 Compsci 201, Spring 2020 41

0 1 2 3 4 5 6 7 8 9 10 11

25 19 17 7 10 6 9 21 13

slide-30
SLIDE 30

Heap is an array, visualize as Tree

Ro Root a at 1 Left child: 2*k Right child: 2*k + 1

4/3/2020 Compsci 201, Spring 2020 42

6

0 1 2 3 4 5 6 7 8 9 10 11

10 7 25 25 19 19 17 17 7 10 6 13 9 9 21 21 13

slide-31
SLIDE 31

Heap is an array, visualize as Tree

No Node 10 10: i index 2 Left child: Right child:

4/3/2020 Compsci 201, Spring 2020 43

6

0 1 2 3 4 5 6 7 8 9 10 11

10 7 25 25 19 19 17 17 7 10 6 13 9 9 21 21 13

Node at e at i index ex k k Left: index 2*k Right: index 2*k+1

slide-32
SLIDE 32

Heap is an array, visualize as Tree

No Node 17 17: i index 4 Left child: Right child:

4/3/2020 Compsci 201, Spring 2020 45

6

0 1 2 3 4 5 6 7 8 9 10 11

10 7 25 25 19 19 17 17 7 10 6 13 9 9 21 21 13

Node at e at i index ex k k Left: index 2*k Right: index 2*k+1

slide-33
SLIDE 33

Properties of a Min-Heap

  • Each

h node i is smaller aller t than i n its c child ildren en

  • Wher

here is is t the m he mini inimal no node? e?

  • At the root of the tree
  • At the front of the array
  • A hea

heap is is alw always bala alanced!

4/3/2020 Compsci 201, Spring 2020 47

slide-34
SLIDE 34

Min-Heap – Where is smallest?

Note each node smaller than children

4/3/2020 Compsci 201, Spring 2020 48

6

0 1 2 3 4 5 6 7 8 9 10 11

10 7 25 25 19 19 17 17 7 10 6 13 9 9 21 21 13

slide-35
SLIDE 35

Remove the minimum element

  • Can

an’t rem emove t the r he root

  • Swap

ap root wit ith la h last elem element in in ar array.

  • Rem

emove m min ( in (no now la last elem element in in ar array)

  • Fix

ix the heap he heap

4/3/2020 Compsci 201, Spring 2020 49

slide-36
SLIDE 36

Remove the minimum

4/3/2020 Compsci 201, Spring 2020 50

6

0 1 2 3 4 5 6 7 8 9 10 11

10 7 25 25 19 19 17 17 7 10 6 13 9 9 21 21 13

slide-37
SLIDE 37

N elements – Time to remove min?

  • Swa

wap

  • Remo

move mi min

  • Adj

Adjust

4/3/2020 Compsci 201, Spring 2020 59

0 1 2 3 4 5 6 7 8 9 10 11

10 7 19 19 17 17 7 10 25 13 9 25 21 21 13 9

slide-38
SLIDE 38

Add element to a min-heap

  • Put

ut t the he elem element a at t the end he end o

  • f the ar

he array

  • Not

a a hea heap any anymore!

  • Bubble e

le element nt u up path t h to fix heap ap!

  • Compare element to parent, swap if needed

4/3/2020 Compsci 201, Spring 2020 61

slide-39
SLIDE 39

Add Element to min-Heap

  • Add 8

dd 8

4/3/2020 Compsci 201, Spring 2020 62

6

0 1 2 3 4 5 6 7 8 9 10 11

10 7 25 25 19 19 17 17 7 10 6 13 9 9 21 21 13

slide-40
SLIDE 40

N elements – Time to add element?

4/3/2020 Compsci 201, Spring 2020 69

6

0 1 2 3 4 5 6 7 8 9 10 11

8 7 25 25 19 19 17 17 7 8 6 10 9 9 21 21 10 13 13

  • Add t

dd to a array

  • Adj

Adjust

slide-41
SLIDE 41

Review ew – Sort with PriorityQueues

  • How can w

n we sort N N elem ement ents u using ng P Priorit ity Q Queue eue?

  • Add all elements to pq, then remove them
  • Every operation is O(log N), so this sort?
  • O(N log N) – basis for hea

heap s sort

4/3/2020 Compsci 201, Spring 2020 71

slide-42
SLIDE 42

WOTO – Priority Queues

  • http://b

://bit.l .ly/20 /201s 1spring2 g20-040 403-2

4/3/2020 Compsci 201, Spring 2020 72

slide-43
SLIDE 43

Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 3 3 of

  • f 4

4/3/2020 Compsci 201, Spring 2020 73

Susan Rodger April 3, 2020

slide-44
SLIDE 44

A Story about Bubble Sort

4/3/2020 Compsci 201, Spring 2020 74

slide-45
SLIDE 45
  • Prof. Owen

Astrachan

  • Ph

PhD at at Duke, , Stayed at ed at D Duke

  • Ha

Hates B Bubble so sort, t thinks it is s the worst rst so sort ever

  • Obse

sessed w with Bubbl bles esort!

4/3/2020 Compsci 201, Spring 2020 75

slide-46
SLIDE 46

Steve Wolfman and Rachel Pottinger, Duke 1997, now Profs at UBC

4/3/2020 Compsci 201, Spring 2020 76

slide-47
SLIDE 47

Wrote a paper

  • “W

“Why bu bubbl bble i is not m my favorite sort”

  • Submit

itted i it t to a conferenc nce

  • It was

as r reject cted!

4/3/2020 Compsci 201, Spring 2020 77

slide-48
SLIDE 48

Another paper accepted!

4/3/2020 Compsci 201, Spring 2020 78

slide-49
SLIDE 49

11/08/77

4/3/2020 Compsci 201, Spring 2020 79

slide-50
SLIDE 50

17 Nov 75 Not needed Can be tightened considerably

4/3/2020 Compsci 201, Spring 2020 80

slide-51
SLIDE 51

Donald Knuth (Turing 1974)

  • “In s

short, t , the b e bubble le s sort seems t to have n e nothing hing to recommend end i it, e , exce cept a a catchy nam name, and and t the he fac act t tha hat it it lea leads t to some inter eresting ing t theo eoretica ical l problem lems.” .”

4/3/2020 Compsci 201, Spring 2020 81

slide-52
SLIDE 52

Jim Gray (Turing 1998)

  • Bubble sort is a good

argument for analyzing algorithm performance. It is a perfectly correct

  • algorithm. But it's

performance is among the worst imaginable. So, it crisply shows the difference between correct algorithms and good algorithms.

(italics ola’s)

slide-53
SLIDE 53

Brian Reid (Hopper Award 1982)

  • Feah. I love bubble sort,

and I grow weary of people who have nothing better to do than to preach about it. Universities are good places to keep such people, so that they don't scare the general public.

(continued)

slide-54
SLIDE 54

Brian Reid (Hopper 1982)

I am quite capable of squaring N with or without a calculator, and I know how long my sorts will bubble. I can type every form of bubble sort into a text editor from memory. If I am writing some quick code and I need a sort quick, as opposed to a quick sort, I just type in the bubble sort as if it were a statement. I'm done with it before I could look up the data type of the third argument to the quicksort library. I have a dual-processor 1.2 GHz Powermac and it sneers at your N squared for most interesting values of N. And my source code is smaller than yours.

Brian Reid who keeps all of his bubbles sorted anyhow.

slide-55
SLIDE 55

Niklaus Wirth (Turing award 1984)

I have read your article and share your view that Bubble Sort has hardly any

  • merits. I think that it is so often

mentioned, because it illustrates quite well the principle of sorting by exchanging. I think BS is popular, because it fits well into a systematic development of sorting

  • algorithms. But it plays no role in

actual applications. Quite in contrast to C, also without merit (and its derivative Java), among programming codes.

slide-56
SLIDE 56

Obama on Sorting

When he was a senator running for President

What is the most efficient way to sort a million 32-bit integers?

4/3/2020 Compsci 201, Spring 2020 87

slide-57
SLIDE 57

Wikipedia page on BubbleSort

  • a

4/3/2020 Compsci 201, Spring 2020 88

slide-58
SLIDE 58

Musical Bubblesort

4/3/2020 Compsci 201, Spring 2020 90

slide-59
SLIDE 59

Compsci 201 201 More Sorti ting, B Backtra ktracking Par art 4 4 of

  • f 4

4/3/2020 Compsci 201, Spring 2020 91

Susan Rodger April 3, 2020

slide-60
SLIDE 60

Backtracking and Blob Fill

  • Explo

lore a a move ( (blo lob f fill ill) if if it it works? F Fab abulous!

  • If it does not work? Undo the move, try again
  • Similar

ilar t to Sudoku s u solving ng? C Crossword p puz uzzles les?

  • Tentatively try number of word, follow through
  • May need to undo and try alternative

4/3/2020 Compsci 201, Spring 2020 92

slide-61
SLIDE 61

Exhaustive Search

  • Can e

n explore e ever ery p possib ible le m move i e in tic-ta tac-to toe

  • Cannot explore every possible move in chess
  • Brute

te-force d doesn sn't w 't work

  • Be smart, try move? Then undo, try another
  • Bac

acktrackin ing in in sea earch t tree ee

  • Smart pruning

4/3/2020 Compsci 201, Spring 2020 93

slide-62
SLIDE 62

N-Queens: Know History

  • Can

an w we e plac lace N N quee ueens o

  • n

n NxN xN boa

  • ard s

so

  • no
  • queen at

en attack cks a another her

  • 4x4 or 8x8 or …

4/3/2020 Compsci 201, Spring 2020 94

slide-63
SLIDE 63

8 Queens – What fun!

4/3/2020 Compsci 201, Spring 2020 95

slide-64
SLIDE 64

Nqueen Concepts

  • For eac

each c column c c in in [0.. 0..N)

  • Try to place queen in each row of column c
  • grid[r][c] ok? Place queen, try c+1
  • If not ok? Or Doesn't work? Try next row, r+1
  • When

hen ha have all q all quee ueens b been een p plac laced?

  • If c == N and success? Done!
  • Can't do column c? return false, c-1 continues

4/3/2020 Compsci 201, Spring 2020 96

slide-65
SLIDE 65

Code for Nqueens Backtracking

https://coursework.cs.duke.edu/201spring20/backtracking-sp20/

  • Done w

ne when hen c c == N

  • Place queens, recurse, unplace and try again
  • Retur

urn t n true

  • All placed
  • Recursive
  • Us

Use myBoard

  • Track moves

4/3/2020 Compsci 201, Spring 2020 97

slide-66
SLIDE 66

Backtracking Summary

  • Enumer

erate a all p possible m le moves/cho choices ices

  • Nqueen? Each column and each row in column
  • Blob-fill? Each neighbor: fill, and unfill
  • Boar

ard often en t two-dimens nsio iona nal a l array/grid id

  • Record move, recurse, undo if not done

4/3/2020 Compsci 201, Spring 2020 98

slide-67
SLIDE 67

Backtracking APTs

  • Often us

use e grid[][] to store s e state/ e/moves

  • In Java this is actually an array of arrays
  • int[][] a = new int[4][4] fo

for e examp mple

  • What is a[0]? What is a[0][0]?
  • Often m

n move m must be explicit licitly u undone ne

  • Sometimes just try everything

4/3/2020 Compsci 201, Spring 2020 99

slide-68
SLIDE 68

Collaborative APT Solving

  • https://w

://www2.cs cs.duke.edu .edu/c /csed/n ed/newap apt/g /gri ridg dgam ame.h .html

  • Sha

hall ll w we e pla lay a a gam ame?

  • Each player plays perfectly
  • If I go her

here, w will y ill you u win? in?

4/3/2020 Compsci 201, Spring 2020 101

slide-69
SLIDE 69

All-seeing and All-knowing

  • Giv

iven a a boar ard, ho how many any w winni inning m moves?

  • Can't tell, can determine all possible moves
  • Make a move, ask if it's a winner
  • Can't tell? Make move and repeat

4/3/2020 Compsci 201, Spring 2020 102

slide-70
SLIDE 70

What can we do with a board?

  • Can y

you d u det eter ermine e if [r][c] i is legal al?

  • [1][0] is legal, why?
  • [3][1] is NOT legal, why?
  • Suppose

e ther ere a e are n e no legal al m moves es? Answer er: Z Zero/0

  • Sup

uppose I I place a an n 'X' a and nd the hen ask

  • How many ways to win does opponent have?
  • If answer is Zero/0, what does placing 'X' do?
  • This l

leads ds to to backtr ktrackin ing, b belie lieve the c code de!!!

".X.X" "..X." ".X.." "...."

4/3/2020 Compsci 201, Spring 2020 103

slide-71
SLIDE 71

APT GridGame Ideas

  • Have bool
  • olean metho

hod winWithBoard(board)

  • For each legal move
  • Place on board – board now changed
  • Call winWithBoard(board) -- if true? I lose
  • Undo move --- take off board and continue
  • If you

u could uld s see ee ahe ahead, y you' u'd k kno now if if the he m move wa was g good.

  • d. winWithBoard is

is an an orac acle

4/3/2020 Compsci 201, Spring 2020 104

slide-72
SLIDE 72

What Do We Believe?

  • Predicti

tions b s by oracles … s …

4/3/2020 Compsci 201, Spring 2020 105

slide-73
SLIDE 73

All-seeing and All-knowing

  • Giv

iven a a boar ard, ho how many any w winni inning m moves?

  • Can't tell, can determine all possible moves
  • Make a move, ask if it's a winner
  • Can't tell? Make move and repeat

4/3/2020 Compsci 201, Spring 2020 106

slide-74
SLIDE 74

All-seeing and All-knowing

  • Given a

n a board, a are t e there a e any m moves possib ible? le?

  • If no moves possible … last move was winner!
  • Last person to place an X wins
  • So, t

, try e every X, w , wit ith eac h each o

  • ne …

ne …

  • Ask recursively if winner
  • Make move and ask …

– Make move and ask …

4/3/2020 Compsci 201, Spring 2020 107

slide-75
SLIDE 75

GridGame backtracking, count wins

private int winCount(char[][] board) { int wins = 0; for(int r=0; r < 4; r++){ for(int c=0; c < 4; c++){ if (canMove(board,r,c)){ board[r][c] = 'X'; int opponentWins = winCount(board); if (opponentWins == 0){ wins += 1; } board[r][c] = '.'; } } } return wins; }

".X.X" "X.X." ".X.." "...." ".X.X" "..X." ".X.." "...." ".X.X" "X.X." ".X.X" "...."

4/3/2020 Compsci 201, Spring 2020 108

slide-76
SLIDE 76

Red to try each open space and …

".X.X" "X.X." ".X.." "...." ".X.X" "..X." ".X.." "...." ".X.X" "X.X." ".X.X" "...." ".X.X" "X.X." ".X.X" "X..." ".X.X" "..X." ".X.." "...." ".X.X" "..X." ".X.." "...X" ".X.X" "X.X." ".X.." "...X" Red loses Red wins!

Make a move, ask oracle (recursion) how many winners after move? Oracle tries all moves and says none … meaning made move winner

4/3/2020 Compsci 201, Spring 2020 109

slide-77
SLIDE 77

GridGame backtracking, count wins

private int winCount(char[][] board) { int wins = 0; for(int r=0; r < 4; r++){ for(int c=0; c < 4; c++){ if (canMove(board,r,c)){ board[r][c] = 'X'; int opponentWins = winCount(board); if (opponentWins == 0){ wins += 1; } board[r][c] = '.'; } } } return wins; }

".X.X" "X.X." ".X.." "...." ".X.X" "..X." ".X.." "...." ".X.X" "X.X." ".X.X" "...."

4/3/2020 Compsci 201, Spring 2020 111

slide-78
SLIDE 78

Don't Know Much about History

  • Usene

net, C , Ches hess, C Chec ecker ers, … …

  • Alan Biermann, Tom Truscott: Internet Pioneer

4/3/2020 Compsci 201, Spring 2020 112

slide-79
SLIDE 79

WOTO on Backtracking

  • http://b

://bit.l .ly/20 /201s 1spring2 g20-040 403-3

4/3/2020 Compsci 201, Spring 2020 113

slide-80
SLIDE 80

Donald Knuth (Turing 1974)

  • Writin

ting multip ltiple le v volume mes “The he Art o

  • f Comput

uter er Program amming ng”

  • Title i

is “Prof

  • fessor

sor o

  • f The

Ar Art of

  • f Comp
  • mputer

Program amming ng” at ” at Stanf nford

  • Pipe O

e Organ i an in h his h home e wi with 812 812 pipes

  • Played

ed t the o

  • rgan

an i in the e Duke C e Chap apel el!

4/3/2020 Compsci 201, Spring 2020 114