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.
283 # Dealing with complex problems: some terms to know
287 ## Divide and Conquer
289 * Split a problem into smaller parts
291 * Combine the sub-solutions
292 * Often leads to logarithmic growth
294 "Guess the number" game
295 * What if I don't tell you the upper limit?
297 ## Dynamic programming
299 Build a soluion bottom-up from subparts
303 * Posh word for
"guess"
316 ## Travelling Salesman Problem
318 Online: http://www.math.uwaterloo.ca/tsp/games/tspOnePlayer.html
320 * But many implementations are Java applets, now a problem with security settings
322 Try Android/iOS apps?
324 ## Change-finding problem
326 Same as the Knapsack problem: M269 Unit
5 Section
3.2, especially Activity
5.9
328 Dynamic programming to find solution
330 ## Ticket to Ride boardgame
334 # Turing and computability
336 (Following [Craig Kaplan's description of the Halting Problem](http://www.cgl.uwaterloo.ca/~csk/halt/))
338 ## The Entscheidungsproblem (Decision problem)
340 Given some axioms, rules of deduction, and a statement (input), can you prove whether the statement follows from the axioms?
342 The rules could be described to a human computer.
344 The computer would either answer
"Yes," "No," or never stop working.
346 This is the Halting problem.
350 # Universal Turing machine
352 .float-right[![A computer](human-computer-worksheet.png)]
354 A Turing machine does one particular job
356 But you can describe how to do that job to another person
358 In other words, you can treat the instructions as the input to another machine
360 A *universal* Turing machine can take the description of any Turing machine and produce the same output
362 * Instruction = input
365 *This* shows that computing as we know it is possible.
376 <script src=
"http://gnab.github.io/remark/downloads/remark-0.6.0.min.js" type=
"text/javascript">
379 <script type=
"text/javascript"
380 src=
"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&delayStartupUntil=configured"></script>
382 <script type=
"text/javascript">
383 var slideshow = remark.create({ ratio:
"16:9" });
388 skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
391 MathJax.Hub.Queue(function() {
392 $(MathJax.Hub.getAllJax()).map(function(index, elem) {
393 return(elem.SourceElement());
394 }).parent().addClass('has-jax');
396 MathJax.Hub.Configured();