1 gentle introduction to programming session 3: recursion
Post on 21-Dec-2015
224 views
TRANSCRIPT
1
Gentle Introduction to Programming
Session 3: Recursion
2
Review• More Scala:
• var / val• Strings & API• Defining variables (type inference)• Variable scope• Importance of style
• Functions• Why do we need them• Types: methods, local (nested), literal, value• Closures• Higher order functions• The functions stack
• More on control structures• if / while / for result in a value
3
Correctness Of Algorithm / Code
דיון
4
Functions
((x : Int) => x * 2)(a)
((x : Int) => x * 2)(5)
((x : Int) => x * 2)5 5
10
5
Higher Order Functions
100
1k
k
sum += ((x:Int) => x)(i)
i = ((x:Int) => x+1)(i)
6
Integration as a Function
Integration under a curve f is approximated by
dx (f(a) + f(a + dx) + f(a + 2dx) + … + f(b))
a bdx
f
7
Integration as a Function (Cont.)
a bdx
f
8
arctan(a) = ∫(1/(1+y2))dy0
a
Integration.scala
9
The Debugger
• Some programs may compile correctly, yet not produce the desirable results
• These programs are valid and correct Scala programs, yet not the programs we meant to write!
• The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program
10
Debugger – Add Breakpoint
• Right click on the desired line
• “Toggle Breakpoint”
11
Debugger – Start Debugging
breakpoint
debug
12
Debugger – Debug Perspective
13
Debugger – Debugging
Current state
Current location
Back to Scala perspective
14
Today• Recursion• Guest lecture by Prof. Ran Canetti 11:10• Home work review• Home work• Arrays (if time allows)
15
The Functions “Stack”
g()->h()
f()->g()
main-> f()
16
Recursive Functions
• How to create a process of unbounded length?
• Needed to solve more complicated problems
• Tower of Hanoi
• Start with a simple example
17
Tower of Hanoi
18
Tower of Hanoi
• How to solve for arbitrary number of disks n?• Let’s name the pegs: source, target, spare• All n disks are initially placed on source peg• Solution:
1. Move n-1 upper disks from source to spare
2. More lower (bigger) disk from source to target
3. Move n-1 disks from spare to target (smaller. Easier?)• Base condition: a single disk
19
Factorial
• As we saw, n! = 1*2*3*… *(n-1)*n
• Thus, we can also define factorial the following way: • 0! = 1 • n! = n*(n-1)! for n>0
(n-1)! * n
RecursiveDefinition
20
A Recursive Definition
• Functions can also call themselves!• However, usually not with the same parameters
• Some functions can be defined using smaller occurrences of themselves
• Every recursive function has a “termination condition”. The function stops calling itself when it is satisfied
21
Example - Factorial
Termination Condition
Recursive Calll
Factorial.scala
22
Example - factorial
factRec(1)
factRec(2)->2*factRec (1)
factRec(3)->3*factRec (2)
main-> factRec (3)
23
Recursive factorial – step by step
FactRec(4)n
4
Returns…
24
Recursive factorial – step by step
FactRec(4)n
4
Returns…4*…
25
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
26
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
27
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…3*…
28
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
29
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
30
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…2*…
31
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
FactRec(1)n
1
Returns…
32
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
FactRec(1)n
1
Returns…
33
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…
FactRec(1)n
1
Returns… 1
34
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…
FactRec(2)n
2
Returns…2*1
35
Recursive factorial – step by step
FactRec(4)n
4
Returns…
FactRec(3)n
3
Returns…3*2
36
Recursive factorial – step by step
FactRec(4)n
4
Returns…4*6
37
General Form of Recursive Algorithms
• Base case: small (non-decomposable) problem• Recursive case: larger (decomposable) problem• At least one base case, and at least one recursive
case.
test + base case recursive case
38
Short Summary
• Design a recursive algorithm by1. Solving big instances using the solution to smaller
instances
2. Solving directly the base cases
• Recursive algorithms have1. test
2. recursive case(s)
3. base case(s)
39
More Examples
40
Example - Modulo
• Given the following iterative version of modulo calculation
Find the recursive definition
Modulo.scala
41
Solution
42
Fibonacci
• “Naturally” recursive• Because the nth term is the sum of the (n-1)th and
(n-2)th terms• Therefore, the recursive definition is:
• fib(1) = 0 ; fib(2) = 1 /* base */• fib(n) = fib(n-1) + fib(n-2)
43
Or, in Scala…Fibonacci.scala
44
Recursion and Efficiency
• The recursive form, however elegant, may be much less efficient
• The number of redundant calls grow exponentially!
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2) Fib(2) Fib(1)
Fib(2)
Fib(1)
Fib(6)
Fib(4)
45
Efficient Recursive Fibonacci
• Pass the values that were already calculated to the recursive function
• This technique is called Memoization
• How would we keep the values that were already calculated?
Fib(5)
Fib(4) Fib(3)
Fib(3) Fib(2) Fib(2) Fib(1)
Fib(2)
Fib(1)
Fib(6)
Fib(4)
48
Odd-Even
• Given a function ‘odd(n : Int) : Boolean’ • Return true on n that are odd, false on even n
• Write a function ‘even(n : Int) : Boolean’ that:• Return true on n that are even, false on odd n
• This is easy
49
Odd-EvenEvenOdd.scala
50
Decimal Binary
• We want to print the binary representation of a decimal number
• Examples:• 0 -> 0• 8 -> 1000• 12 -> 1100• 31 -> 11111
51
Decimal Binary Recursively
• The conversion of a number d from decimal to binary:• If d is 0 or 1 – write d to the left and stop, else:• If d is even, write ‘0’ to the left• If d is odd, write ‘1’ to the left• Repeat recursively with floor(d/2)
52
Example: d = 14
d Output at the end of stage Action at the end of stage
14 0 Insert 0 to left of output; divide d by 2
7 10 Insert 1 to left of output; divide d by 2 and round down
3 110 Insert 1 to left of output; divide d by 2 and round down
1 1110 Insert 1 to left of output; return.
53
Solution Dec2Bin.scala
54
Today• Recursion• Guest lecture by Prof. Ran Canetti• Home work review• Home work• Arrays (if time allows)
55
Approximating Square Root
• Given integer x > 0, how to find an approximation of x?
• Newton was the first to notice that for any positive n, and when x0=1, the following series converges to sqrt(n):
56
Algorithm
x = 2 g = 1x/g = 2 g = ½ (1+ 2) = 1.5
x/g = 4/3 g = ½ (3/2 + 4/3) = 17/12 = 1.416666
x/g = 24/17 g = ½ (17/12 + 24/17) = 577/408 = 1.4142156
• Algorithm:• Make a guess g• Improve the guess by averaging g, x/g• Keep improving the guess until it is good enough
• Example: calculate the square root of 2
57
Exercise 1
• Write a program that receives from the user:• An integer x > 0• A double representing the approximation’s accuracy
• Calculates an approximation of x within the required accuracy
Use the function Math.abs(x) which returns the absolute value of x
58
Solution ApproxSQRT.scala
59
Exercise 2
Write a function that uses the formula :2/6=1/1+1/4+1/9+1/16+…+1/n2 (where n goes to infinity)
in order to approximate . The function should accept an argument n which determines the number of terms in the formula. It should return the approximation of
Write a program that gets an integer n from the user, and approximate using n terms of the above formula• Use a nested function sum, with signature:
60
Solution ApproxPI.scala
61
Exercise 3
• Write a function deriv: • Input: a function f (Double=>Double), accuracy dx• Output: function df (Double=>Double), the derivative
of f. • df (x) = (f(x+dx) – f(x))/dx• Define a few simple functions (linear, square) and
calculate their derivative at various points received by command line arguments
62
Usage Example
// the function you want to derive
def f(x : Double) : Double = x * x// resolution/accuracy/granularity of derivative
val dx = 0.001 /* this is the invokation of the function you
are supposed to implement*/
val df = deriv(f,dx) // print the derivative of f(x) at x = 10
println(df(10))
63
SolutionDerivative.scala
64
Today• Recursion• Guest lecture by Prof. Ran Canetti• Home work review• Home work• Arrays (if time allows)
65
Exercise 1
• Write a program that receives two non-negative integers and computes their product recursively
• Hint: Notice that the product a*b is actually a+a+…+a (b times). How does this help us define the problem recursively?
66
Exercise 2
• Given the following iterative version of sum-of-digits calculation
Write the recursive definition
67
Exercise 3
• Write a function that simulates print on positive integers
• The function should print one digit at time• Example:
• printRec(1234) 1234
68
Today• Recursion• Guest lecture by Prof. Ran Canetti• Home work review• Home work• Arrays (if time allows)
69
Arrays
• Array: sequential block of memory that holds variables of the same type
• Array can be declared for any type• Example: new Array[Int](3)
• Examples:• list of students’ marks• series of numbers entered by user• vectors• matrices
70
Arrays in Memory
• Sequence of variables of specified type• The array variable itself holds the address in
memory of beginning of sequence• Example: val s = new Array[Double](10)
• The k-th element of array A is specified by A[k-1] (0 based)
0 1 2 3 4 5 6 7 8 9
s
……
71
Example - Initialization
72
Arrays in Memory
• Access array’s content
• Change array’s content
73
Example
Array.scala
74
foreach, filter
• Iterates over arrays (and other containers)
• foreach – for each element apply a given function
• filter – create a new container containing only elements that pass the given Boolean-function
75
Example – Print Arrays PrintArray.scala
76
Example – filter
77
Example – Find MinimumFindMin.scala
78
HW on Arrays: Exercise 4
Write a program that gets 10 numbers from the user.It then accepts another number and checks to see ifthat number was one of the previous ones.
Example 1:Please enter 10 numbers:1 2 3 4 5 6 7 8 9 10Please enter a number to search for: 8Found it!
Example 2:Please enter 10 numbers:1 2 3 4 5 6 7 8 9 10Please enter a number to search for: 30Sorry, it’s not there