1 Gentle Introduction to Programming Session 3: Recursion.

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

The debugger Some programs may compile correctly, yet not produce the desirable results. These programs are valid and correct C programs, yet not the programs.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 16: Recursion.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
1 Gentle Introduction to Programming Session 4: Arrays, Sorting, Efficiency.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 Gentle Introduction to Programming Session 2: Functions.
1 Chapter 1: Introduction What you have learnt in Comp1220 or Comp1170? What will be taught in Comp 1200? - more Abstract Data Types -efficient algorithms.
Programming Recursion “To Iterate is Human, to Recurse, Divine” -- L. Peter Deutsch.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
1 Gentle Introduction to Programming Tirgul 1: Shell and Scala “hands on” in the lab.
1 Gentle Introduction to Programming Session 3: Higher Order Functions, Recursion.
1 Gentle Introduction to Programming Session 5: Memory Model, Object Oriented Programming.
Exercise 4 Recursion. Functions – a short reminder a group of variables and statements that is assigned a name a sub-program  inside main we can call.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
1 Gentle Introduction to Programming Tirgul 2: Scala “hands on” in the lab.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
1 Gentle Introduction to Programming Session 2: Functions.
1 Gentle Introduction to Programming Session 4: Arrays.
Data Structures Using C++ 2E Chapter 6 Recursion.
Data Structures Using C++ 2E Chapter 6 Recursion.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementation:
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Recursion. Functions – reminder A function can call other functions. Return causes the execution of the function to terminate and returns a value to the.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Basic Mathematics Chapter 1 (1.2 and 1.3) Weiss. Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion If we have time: live demo!!!
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
1 Programming for Engineers in Python Autumn Lecture 8: Recursion.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
Recursion ● Recursion or Iteration ● A Common Recursive Design Pattern ● Computing factorials ● Searching a filesystem tree ● Faster exponentiation ● Slow.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Chapter 15 Recursion.
Fibonacci Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition:
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Algorithm Analysis (for Divide-and-Conquer problems)
Chapter 12 Recursion (methods calling themselves)
Dr. Sampath Jayarathna Cal Poly Pomona
ITEC324 Principle of CS III
Presentation 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) 55 10

5 Higher Order Functions 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 b dx f

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

8 arctan(a) = ∫(1/(1+y 2 ))dy 0 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 Recursive Definition

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

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

50 Decimal  Binary We want to print the binary representation of a decimal number Examples: 0 -> 0 8 -> > > 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 140 Insert 0 to left of output; divide d by 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 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 x 0 =1, the following series converges to sqrt(n):

56 Algorithm x = 2g = 1 x/g = 2g = ½ (1+ 2) = 1.5 x/g = 4/3g = ½ (3/2 + 4/3) = 17/12 = x/g = 24/17g = ½ (17/ /17) = 577/408 = 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/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 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 = /* 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 Solution Derivative.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) 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 Minimum FindMin.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 if that number was one of the previous ones. Example 1: Please enter 10 numbers: Please enter a number to search for: 8 Found it! Example 2: Please enter 10 numbers: Please enter a number to search for: 30 Sorry, it’s not there