logic, algorithms and data structures · m1 logic, algorithms and data structures recursion and...
TRANSCRIPT
M1
Logic, Algorithms and Data StructuresRecursion and Stacks
By: Jonas Öberg
What is recursion?
Quick answer:
A recursive function is a function which uses itself
Example
f( n ) = 2⋅f (n -1) if n >= 1otherwise1
We define by the use of
What is recursion?
What does it do??
f(3)
{ 3 >= 1 }f(3) = 2 * f(3-1) = 2 * f(2)
f(3) = 2 * f(2)f(2)
{ 2 >= 1 }f(2) = 2 * f(2-1) = 2 * f(1)
f(3) = 2 * 2 * f(1)f(1)
{ 1 >= 1}
f(1) = 2 * f(1-1) = 2 * f(0)
f( n ) = 2⋅f (n -1) if n >= 1otherwise1
f(3) = 2 * 2 * 2 * f(0) f(0) { 0 >= 1 } f(0) = 1f(3) = 2 * 2 * 2 * 1f(3) = 8
How do we write recursively?
Problem:Write a function that computes the smallest element in a set.
Sample data:A = { 7, 3, 5, 9, 2, 12 }
Stated goal:f({7, 3, 5, 9, 2, 12}) = 2
How to think
Assume that the function already does its job for a subset of A, ie. A-{x}
Our parts: f (A-{x}) and x
To this, we only need to add some glue and/or gaff tape
f (A-{x})
How to think
Given:A = {7, 3, 5, 9, 2, 12}x = 7
We assume that:f(A-{x}) = 2
We want a function such that:f(A) = f(A-{x}) ... x = 2
How to think
So, we want to find a function which solves:f(A) = f(A-{x}) ... x = 2
f(A) = 2 ... 7 = 2
This is what we wanted: write a function that computes the smallest element in a set.
f(A) = min(2, 7) = 2
How to think
min(x, y) = if x <= y then x else y
So, min(x, y) will be our glue!
f(A) = min(f(A-{x}), x)
How to think
But there's something missing here!
f( A ) = min(f (A-{x}), x)
The Base Case
Computing f({3, 5, 7})
f({3, 5, 7}) =
min(3, f({5, 7})) =
min(3, min(5, f({7}))) =
min(3, min(5, min(7, f({})))) =
min(3, min(5, min(7, min({}, f({}))))) =
min(3, min(5, min(7, min({}, min({}, f({}))))))) ...
We need to define f({}) This is called the “Base Case”
f ( A ) = min( x, f(A –{x}))
Implementing the base case
What's the smallest value of an empty set?
∞
f( A ) = ∞ , if A = {}min(f (A-{x}), x) , otherwise
Implementation
f( A ) = ∞ , if A = {}min(f (A-{x}), x) , otherwise
int setmin(Set a){
if (a.isEmpty()) { return Integer.MAX_VALUE; }
Iterator<Integer> i = a.iterator();int x = i.next(); i.remove();Return Math.min(x, setmin(a));
}
Computing faculty
f(5) = 5 * 4 * 3 * 2 * 1 = 120
Assume that f(4) = 24 already works Then,
f(5) = 5 * f(4)
f(x) = x * f(x-1)
Faculty base case
f( x ) = 1 , if x = 1x * f (x-1) , otherwise
int faculty(int x){
if (x == 1) { return 1; }
return x * faculty(x - 1);}
f(5) = 5 * f(4) = 5 * 4 * f(3) = 5 * 4 * 3 * f(2) = 5 * 4 * 3 * 2 * f(1) = 5 * 4 * 3 * 2 * 1 = 120
Stacks
When is the stack used?
“Kalle”
Stack
main()function(1, “Kalle”, 34);
function(a, b, c)List l = new ArrayList();l.add(b);
34
1
b
Stacks when recursing
faculty(5)5 * faculty(4)5 * 4 * faculty(3)5 * 4 * 3 * faculty(2)5 * 4 * 3 * 2 * faculty(1)5 * 4 * 3 * 2 * 1
4
Stack
321
5 f( x ) = 1 , if x = 1x * f (x-1) , otherwise
624120
public class RecHelloWorld { public static void write_string (String s) { System.out.printf("\n%s\n", s); write_string(s); } public static void main(String[] args) { write_string("Hello World"); }}
Hello WorldHello WorldHello WorldHello WorldHello WorldException in thread "main" java.lang.StackOverflowError
Tower of Hanoi
Algorithm
Total of rings = n Step 1: Move rings n-1 to Help tower Step 2: Move ring n to Goal tower Step 3: Move rings n-1 to Goal tower
Algorithm
Base case: moving ring 1 from Start to Goal Assume that we have a function to move rings
n-1. Solve the problem for moving ring n.
Algorithm
public static void move(int nr, String from, String to) { System.out.printf("%2d: Moving ring nr %d from %s to %s\n", i, nr, from, to);}
Algorithm
public static void tower(int nr, String start, String goal, String help) { if (nr == 1) //Base case move(1, start, goal); else { tower(nr – 1, start, help, goal); move(nr, start, goal); tower(nr – 1, help, goal, start); }}
Step 1: Move rings n-1 to Help tower Step 2: Move ring n to Goal tower Step 3: Move rings n-1 to Goal tower
public class Hanoi { public static int i = 0; // global variable to keep track of method calls public static void move(int nr, String from, String to) { i++; System.out.printf("%2d: Moving ring nr %d from %s to %s\n", i, nr, from, to); }
public static void tower(int nr, String start, String goal, String help) { if (nr == 1) //Base case move(1, start, goal); else { tower(nr – 1,start, help, goal); move(nr, start, goal); tower(nr – 1, help, goal, start); } }
public static void main(String[] args) { int nr = Integer.parseInt(args[0]); tower(nr,"Start Tower", "Goal Tower", "Help Tower"); }}
jonas@anheg:~> java Hanoi 3 1: Moving ring nr 1 from Start Tower to Goal Tower 2: Moving ring nr 2 from Start Tower to Help Tower 3: Moving ring nr 1 from Goal Tower to Help Tower 4: Moving ring nr 3 from Start Tower to Goal Tower 5: Moving ring nr 1 from Help Tower to Start Tower 6: Moving ring nr 2 from Help Tower to Goal Tower 7: Moving ring nr 1 from Start Tower to Goal Tower
Call tree
Labyrinth
Code snippet
RPN calculator
2 1 + 4 * 72 / 5 + 1
Stack
23412726511
RPN calculator
2 1 5 6 * * +
Stack
2156303032
Koch snowflakes1. Start with an equilateral triangle2. Divide each line in turn in three parts3. Draw another equilateral triangle extending from the middle4. Repeat 2
Fractal grammar
F = “Move forward+ = turn left 60 degrees- = turn right 60 degrees
Turtle graphics
Imagine that you're a turtle!
F + + F + + F
Fractal grammar
F = Move forward+ = turn left 60 degrees- = turn right 60 degrees
Koch snowflakeAxiom: F + + F + + FRules: F := F – F + + F - F
Alternatives to Koch
Cesaro fractal
Serpinski triangle
A, B = Move forward+ = turn left 60 degrees- = turn right 60 degrees
Serpinski triangleAxiom: ARules: A := B – A – B and B := A + B + A
Fractal plant
F = Move forward-/+ = turn right/left 25 degreesX = noop[ = save position and angle to stack] = restore position and angle from stack
Fractal plantAxiom: XRules: X := F-[[X]+X]+F[+FX]-X and F := FF
Fractal plant result
Of course, there's work to do..