4 <title>Algorithms
</title>
5 <meta http-equiv=
"Content-Type" content=
"text/html; charset=UTF-8"/>
6 <style type=
"text/css">
15 h1 { font-size:
3em; }
16 h2 { font-size:
2em; }
17 h3 { font-size:
1.6em; }
19 text-decoration: none;
22 -moz-border-radius:
5px;
23 -web-border-radius:
5px;
31 text-shadow:
0 0 20px #
333;
37 text-shadow:
0 0 20px #
333;
51 <textarea id=
"source">
55 ## What's all the fuss about?
61 .indexlink[[Index](index.html)]
65 # What is an algorithm? What is a computer?
67 Back when computers were human...
70 * (Small) working memory
71 * As much notepaper as you wanted
76 Simplified human computer.
78 * (Instructions + memory) → Finite number of states
79 * (States similar to places on a flowchart)
80 * Notepaper → tape (with limited symbols)
82 Algorithm is the instructions
84 (See TU100 Block
2 Part
1, M269 Unit
2)
88 # Sequence, selection, repetition
90 Repetition == iteration or recursion
96 ![left-aligned Growth rates ](big-o-chart-smaller.png) .float-right[![right-aligned Growth rates ](big-o-chart-
2-smaller.png)]
98 `\(f(n) \text{ is } O(g(n)) \quad\text{ if }\quad |f(n)| \le \; M |g(n)|\text{ for all }n \ge N\)`
101 # Complexity classes we care about
103 * Exponential or bigger (
2<sup>*n*
</sup>, *e*
<sup>*n*
</sup>, or *n*!)
104 * Polynomial (*n*
<sup>*k*
</sup>)
106 * Sub-linear (log *n*)
110 * polynomial or smaller is considered tractable
111 * anything exponential or larger is intractable
113 (Exceptions exist in practice.)
117 # Anagrams version
1: checking off
123 for character in word1:
124 for pointer in range(len(word2)):
125 if character == word2[pointer]:
126 word2[pointer] = None
132 Nested loops: complexity is *O*(*n*₁ × *n*₂), or *O*(*n*²).
136 Can anyone see the bug?
140 word1 =
"cat", word2 =
"catty"
144 # Anagrams version
1a: checking off (fixed)
150 for character in word1:
151 for pointer in range(len(word2)):
152 if character == word2[pointer]:
153 word2[pointer] = None
156 for pointer in range(len(word2)):
157 if word2[pointer] != None:
164 # Anagrams version
2: sort and comapre
169 return sorted(word1) == sorted(word2)
172 What's the complexity of `sorted`? What's the complexity of `==`?
176 # Anagrams version
2a: sort and comapre
181 sorted_word1 = sorted(word1)
182 sorted_word2 = sorted(word2)
185 for i in range(len(sorted_word1)):
186 if sorted_word1[i] != sorted_word2[i]:
191 One `for` in the comparison, so its complexity is *O*(*n*).
193 (`len` is also *O*(*n*))
195 What's the complexity of `sorted`?
199 # Anagrams version
2a': sort and comapre, idiomatic
204 sorted_word1 = sorted(word1)
205 sorted_word2 = sorted(word2)
208 for l1, l2 in zip_longest(sorted_word1, sorted_word2):
214 `zip_longest` is lazy, so still *O*(*n*).
216 (Can't use `zip` as it truncates the longest iterable, giving the same bug as number
1)
218 Still dominated by the *O*(*n* log *n*) of `sorted`.
222 # Anagrams version
3: permutations
228 for w in permutations(word1):
234 (Code for `permutations` is complex.)
236 How many permutations are there?
240 # Anagrams version
4: counters
249 counts1[num_of(c)] +=
1
252 counts2[num_of(c)] +=
1
256 if counts1[i] != counts2[
1]:
261 Three `for`s, but they're not nested. Complexity is *O*(*n*₁ + *n*₂ +
26) or *O*(*n*).
263 `dict`s seem a natural way of representing the count. What do you need to be careful of?
265 (Alternative: maintain a single list of differences in letter counts. Initialise to all zero, should be all zero when you've finished.)
267 Notice: trading space for time.
271 # Finding all anagrams
273 Given a `wordlist` and a `word`, find all anagrams of `word` in `wordlist`.
275 * How does your answer change if you know you need to do this just once, or millions of times?
277 # Anagrams of phrases
279 Given a wordlist and a phrase, find another phrase that's an anagram.
287 Don't forget bogosort!
291 # Dealing with complex problems: some terms to know
295 ## Divide and Conquer
297 * Split a problem into smaller parts
299 * Combine the sub-solutions
300 * Often leads to logarithmic growth
302 "Guess the number" game
303 * What if I don't tell you the upper limit?
305 ## Dynamic programming
307 Build a soluion bottom-up from subparts
313 * Posh word for
"guess"
323 * some money and a set of coin denominations,
327 * the smallest number of coins to make that total.
329 ## Approach
1: greedy
333 Pick the biggest coin you can
336 Only works in some cases
338 (What the best way to make
7p if you have
1p,
3p,
4p,
5p coins?)
342 # Making change
2: exhaustive search
344 .float-right[![Ticket to Ride](make-change.dot.png)]
346 Make a tree of change-making.
352 # Making change
3: dynamic programming
358 0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ...
359 -|-|-|-|-|-|-|-|-|-|-|-
360 (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | ...
364 0* |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ...
365 -|-|-|-|-|-|-|-|-|-|-|-
366 (
0,
0,
0) | (
1,
0,
0) | (
0,
1,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
1) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | ...
370 0 |
1* |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ...
371 -|-|-|-|-|-|-|-|-|-|-|-
372 (
0,
0,
0) | (
1,
0,
0) | (
0,
1,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
1) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | ...
376 0 |
1 |
2* |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ...
377 -|-|-|-|-|-|-|-|-|-|-|-
378 (
0,
0,
0) | (
1,
0,
0) | (
0,
1,
0) | (
1,
1,
0) | (
0,
2,
0) | (
0,
0,
1) | (
0,
0,
0) | (
0,
1,
1) | (
0,
0,
0) | (
0,
0,
0) | (
0,
0,
0) | ...
382 0 |
1 |
2 |
3* |
4 |
5 |
6 |
7 |
8 |
9 |
10 | ...
383 -|-|-|-|-|-|-|-|-|-|-|-
384 (
0,
0,
0) | (
1,
0,
0) | (
0,
1,
0) | (
1,
1,
0) | (
0,
2,
0) | (
0,
0,
1) | (
0,
0,
0) | (
0,
1,
1) | (
1,
1,
1) | (
0,
0,
0) | (
0,
0,
0) | ...
390 ## Travelling Salesman Problem
392 .float-right[![Ticket to Ride](ticket-to-ride-small.jpg)]
396 http://www.math.uwaterloo.ca/tsp/games/tspOnePlayer.html
398 * But many implementations are Java applets, now a problem with security settings
400 Try Android/iOS apps?
402 ## Ticket to Ride boardgame
410 # Turing and computability
412 (Following [Craig Kaplan's description of the Halting Problem](http://www.cgl.uwaterloo.ca/~csk/halt/))
414 ## The Entscheidungsproblem (Decision problem)
416 Given some axioms, rules of deduction, and a statement (input), can you prove whether the statement follows from the axioms?
418 The rules could be described to a human computer.
420 The computer would either answer
"Yes," "No," or never stop working.
422 This is the Halting problem.
426 # Universal Turing machine
428 .float-right[![A computer](human-computer-worksheet.png)]
430 A Turing machine does one particular job
432 But you can describe how to do that job to another person
434 In other words, you can treat the instructions as the input to another machine
436 A *universal* Turing machine can take the description of any Turing machine and produce the same output
438 * Instruction = input
441 *This* shows that computing as we know it is possible.
452 <script src=
"http://gnab.github.io/remark/downloads/remark-0.6.0.min.js" type=
"text/javascript">
455 <script type=
"text/javascript"
456 src=
"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&delayStartupUntil=configured"></script>
458 <script type=
"text/javascript">
459 var slideshow = remark.create({ ratio:
"16:9" });
464 skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
467 MathJax.Hub.Queue(function() {
468 $(MathJax.Hub.getAllJax()).map(function(index, elem) {
469 return(elem.SourceElement());
470 }).parent().addClass('has-jax');
472 MathJax.Hub.Configured();