Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Gentle Introduction to Programming Session 3: Recursion.

Similar presentations


Presentation on theme: "1 Gentle Introduction to Programming Session 3: Recursion."— Presentation transcript:

1 1 Gentle Introduction to Programming Session 3: Recursion

2 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 3 Correctness Of Algorithm / Code דיון

4 4 Functions ((x : Int) => x * 2)(a) ((x : Int) => x * 2)(5) ((x : Int) => x * 2) 55 10

5 5 Higher Order Functions sum += ((x:Int) => x)(i) i = ((x:Int) => x+1)(i)

6 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 b dx f

7 7 Integration as a Function (Cont.) a b dx f

8 8 arctan(a) = ∫(1/(1+y 2 ))dy 0 a Integration.scala

9 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 10 Debugger – Add Breakpoint Right click on the desired line “Toggle Breakpoint”

11 11 Debugger – Start Debugging breakpoint debug

12 12 Debugger – Debug Perspective

13 13 Debugger – Debugging Current state Current location Back to Scala perspective

14 14 Today Recursion Guest lecture by Prof. Ran Canetti 11:10 Home work review Home work Arrays (if time allows)

15 15 The Functions “Stack” g() ->h() f() ->g() main -> f()

16 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 17 Tower of Hanoi

18 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 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 Recursive Definition

20 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 21 Example - Factorial Termination Condition Recursive Calll Factorial.scala

22 22 Example - factorial factRec (1) factRec (2) ->2* factRec (1) factRec (3) ->3* factRec (2) main -> factRec (3)

23 23 Recursive factorial – step by step FactRec(4) n 4 Returns…

24 24 Recursive factorial – step by step FactRec(4) n 4 Returns… 4*…

25 25 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…

26 26 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…

27 27 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*…

28 28 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns…

29 29 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns…

30 30 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… 2*…

31 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 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 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 34 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… 2*1

35 35 Recursive factorial – step by step FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*2

36 36 Recursive factorial – step by step FactRec(4) n 4 Returns… 4*6

37 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 38 Short Summary Design a recursive algorithm by 1. Solving big instances using the solution to smaller instances 2. Solving directly the base cases Recursive algorithms have 1. test 2. recursive case(s) 3. base case(s)

39 39 More Examples

40 40 Example - Modulo Given the following iterative version of modulo calculation Find the recursive definition Modulo.scala

41 41 Solution

42 42 Fibonacci “Naturally” recursive Because the n th 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 43 Or, in Scala… Fibonacci.scala

44 44 Recursion and Efficiency The recursive form, however elegant, may be much less efficient The number of redundant calls grow exponentially! Fib(6) Fib(4)

45 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(6) Fib(4)

46 46 Fibonacci with Memoization int main(void) { int fib[SIZE],n,i; fib[1] = 0; fib[2] = 1; for (i = 3; i < SIZE; ++i) fib[i] = -1; printf("Please enter a non-negative number\n"); scanf("%d",&n); printf("fib(%d) = %d\n",n,fib_rec_mem(n,fib)); return 0; }

47 47 Fibonacci with Memoization int fib_rec_mem(int n,int fib[]) { if (fib[n] != -1) return fib[n]; fib[n] = fib_rec_mem(n-1,fib) + fib_rec_mem(n-2,fib); return fib[n]; }

48 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 49 Odd-Even EvenOdd.scala

50 50 Decimal  Binary We want to print the binary representation of a decimal number Examples: 0 -> 0 8 -> 1000 12 -> 1100 31 -> 11111

51 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 52 Example: d = 14 d Output at the end of stage Action at the end of stage 140 Insert 0 to left of output; divide d by 2 710 Insert 1 to left of output; divide d by 2 and round down 3110 Insert 1 to left of output; divide d by 2 and round down 11110 Insert 1 to left of output; return.

53 53 Solution Dec2Bin.scala

54 54 Today Recursion Guest lecture by Prof. Ran Canetti Home work review Home work Arrays (if time allows)

55 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 x 0 =1, the following series converges to sqrt(n):

56 56 Algorithm x = 2g = 1 x/g = 2g = ½ (1+ 2) = 1.5 x/g = 4/3g = ½ (3/2 + 4/3) = 17/12 = 1.416666 x/g = 24/17g = ½ (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 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 58 Solution ApproxSQRT.scala

59 59 Exercise 2 Write a function that uses the formula :  2 /6=1/1+1/4+1/9+1/16+…+1/n 2 (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 60 Solution ApproxPI.scala

61 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 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 63 Solution Derivative.scala

64 64 Today Recursion Guest lecture by Prof. Ran Canetti Home work review Home work Arrays (if time allows)

65 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 66 Exercise 2 Given the following iterative version of sum- of-digits calculation Write the recursive definition

67 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 68 Today Recursion Guest lecture by Prof. Ran Canetti Home work review Home work Arrays (if time allows)

69 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 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) 0123456789 s ……

71 71 Example - Initialization

72 72 Arrays in Memory Access array’s content Change array’s content

73 73 Example Array.scala

74 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 75 Example – Print Arrays PrintArray.scala

76 76 Example – filter

77 77 Example – Find Minimum FindMin.scala

78 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 if that number was one of the previous ones. Example 1: Please enter 10 numbers: 1 2 3 4 5 6 7 8 9 10 Please enter a number to search for: 8 Found it! Example 2: Please enter 10 numbers: 1 2 3 4 5 6 7 8 9 10 Please enter a number to search for: 30 Sorry, it’s not there


Download ppt "1 Gentle Introduction to Programming Session 3: Recursion."

Similar presentations


Ads by Google