39
Methods(3) Dr. Hakem Beitollahi Computer Engineering Department Soran University Lecture 6

Lecture 7

Embed Size (px)

Citation preview

Methods(3)

Dr. Hakem Beitollahi

Computer Engineering DepartmentSoran University

Lecture 6

Outline

Random-Number Generation Example: Game of Chance Recursion Method Overloading

Methods(III)— 2

Random-Number Generation (I) The element of chance

Games, Casinos, Simulation The element of chance can be introduced into computer

applications with the Random class Consider the following statements:

The Next method generates a positive int value between zero and the constant Int32.MaxValue.

the value 2,147,483,647 Every value in this range has an equal chance

Methods(III)— 3

Random randomObject = new Random();int randomNumber = randomObject.Next();

Random-Number Generation (II) The range of values produced directly by Next often is

different from the range of values required in a particular application.

E.g., coin-tossing might require only 0 for “heads” and 1 for “tails.”

E.g., A six-sided die would require random integers in the range 1–6.

The one-argument version of method Next returns values in the range from 0 up to (but not including) the value of that argument.

produces values from 0 through 5.

Methods(III)— 4

value = randomObject.Next( 6 );

Random-Number Generation (III)

The two-argument version of method Next allows us to shift and scale the range of numbers.

to produce integers in the range from 1 to 6. Let’s see an example

The following program simulates 20 rolls of a six-sided die and shows the integer value of each roll.

Methods(III)— 5

value = randomObject.Next( 1, 7 );

An Example

Methods(III)— 6

Example: The Windows application of the next program simulates rolls of four dice.

Methods(III)— 7

Methods(III)— 8

Game of Chance (Dice Game)

Methods(III)— 9

Dice Game (I) Rules of the game

After the first Roll of the Dice, the player wins if the Sum is 7 or 11. If the SUM is 2 or 3 the player loses Otherwise the sum obtained on the first ROLL is referred to as a POINT On the second ROLL the player wins if the SUM = POINT The player loses if the SUM is 7 Otherwise, the player must Roll until he/she wins or loses ( and

RESETS) Example

display1 = 4, display2 = 3 win = 1, loss = 0 display1 = 5, display2 = 4 win = x, loss = x

o Sum = 9 display1 = 3, display2 = 5 win = x, loss = x display1 =2, display2 = 6 win = x, loss =x display1 = 6, display2= 3 win = 1, loss = 0

Methods(III)— 10

Dice Game (II)

Methods(III)— 11

Recursion

Methods(III)— 12

Recursive (I) Recursive method

A method that calls itself, either directly, or indirectly (through another method)

Recursion Base case(s)

o The simplest case(s), which the method knows how to handle For all other cases, the method typically divides the

problem into two conceptual pieceso A piece that the method knows how to do o A piece that it does not know how to do

Slightly simpler or smaller version of the original problem

Methods(III)— 13

Recursive (II) Recursive call (also called the recursion

step)

The method launches (calls) a fresh copy of itself to work on the smaller problem

Can result in many more recursive calls, as the method keeps dividing each new problem into two conceptual pieces

This sequence of smaller and smaller problems must eventually converge on the base caseo Otherwise the recursion will continue forever

Methods(III)— 14

Recursive (III) Factorial

The factorial of a nonnegative integer n, written n! (and pronounced “n factorial”), is the producto n · (n – 1) · (n – 2) · … · 1

Recursive definition of the factorial methodo n! = n · (n – 1)! o Example

5! = 5 · 4 · 3 · 2 · 15! = 5 · ( 4 · 3 · 2 · 1)5! = 5 · ( 4! )

Methods(III)— 15

Recursive (IV)

Methods(III)— 16

Recursive evaluation of 5!.

Factorial implementation using recursive method

Methods(III)— 17

First call to factorial function

Base cases simply return 1

Recursive call to factorial function with a slightly smaller problem

Common Programming Error Either omitting the base case, or writing

the recursion step incorrectly so that it does not converge on the base case, causes “infinite” recursion, eventually exhausting memory. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

Methods(III)— 18

Recursive (V) The Fibonacci series

0, 1, 1, 2, 3, 5, 8, 13, 21, … Begins with 0 and 1 Each subsequent Fibonacci number is the

sum of the previous two Fibonacci numbers can be defined recursively as follows:

o fibonacci(0) = 0o fibonacci(1) = 1o fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2)

Methods(III)— 19

Recursive (VI)

Methods(III)— 20

Set of recursive calls to function fibonacci.

Fibonacci implementation

Methods(III)— 21

Recursive calls to fibonacci function

Base cases

Recursive (VII) Caution about recursive programs

Each level of recursion in method fibonacci has a doubling effect on the number of method calls

o i.e., the number of recursive calls that are required to calculate the nth Fibonacci number is on the order of 2n

o 20th Fibonacci number would require on the order of 220 or about a million calls

o 30th Fibonacci number would require on the order of 230 or about a billion calls.

Exponential complexityo Can humble even the world’s most powerful computers

Methods(III)— 22

Performance Tip Avoid Fibonacci-style recursive programs

that result in an exponential “explosion” of calls.

Methods(III)— 23

Recursion vs. Iteration

Methods(III)— 24

Recursion vs. Iteration (I) Both are based on a control statement

Iteration – repetition structure Recursion – selection structure

Both involve repetition Iteration – explicitly uses repetition structure Recursion – repeated function calls

Both involve a termination test Iteration – loop-termination test Recursion – base case

Methods(III)— 25

Recursion vs. Iteration (II) Both gradually approach termination

Iteration modifies counter until loop-termination test fails

Recursion produces progressively simpler versions of problem

Both can occur infinitely Iteration – if loop-continuation condition never

fails Recursion – if recursion step does not simplify

the problem

Methods(III)— 26

Iterative implementation of factorial method

Methods(III)— 27

Recursion vs. Iteration (III) Negatives of recursion

Overhead of repeated method callso Can be expensive in both processor time and memory space

Each recursive call causes another copy of the method (actually only the method’s variables) to be created

o Can consume considerable memory Iteration

Normally occurs within a method Overhead of repeated method calls and extra memory

assignment is omitted

Methods(III)— 28

Recursion usages Usage of recursive method

Quicksort technique is better to implement with recursive.

Several neural networks can only be solved using recursive methods.

Sometimes recursive methods are easier to understand than iteration methods.

Methods(III)— 29

Software Engineering Observation Any problem that can be solved recursively can

also be solved iteratively (nonrecursively). A recursive approach is normally chosen in preference to an iterative approach when the recursive approach more naturally mirrors the problem and results in a program that is easier to understand and debug. Another reason to choose a recursive solution is that an iterative solution is not apparent.

Methods(III)— 30

Performance Tip Avoid using recursion in performance

situations. Recursive calls take time and consume additional memory.

Methods(III)— 31

Common Programming Error Accidentally having a nonrecursive

function call itself, either directly or indirectly (through another function), is a logic error.

Methods(III)— 32

Method Overloading

Methods(III)— 33

Method Overloading (I) Method Overloading

Overloaded methods haveo Same nameo Different sets of parameters

Compiler selects the proper method to execute based on number, types and order of arguments in the method call

Commonly used to create several methods of the same name that perform similar tasks, but on different data types

Methods(III)— 34

Method Overloading (II) A method name can be overloaded

Two methods with the same name but with different interfaceso Typically this means different formal parameter

lists Difference in number of parameters

Min(a, b, c)

Min(a, b) Difference in types of parameters

Min(10, 20)

Min(4.4, 9.2)

Methods(III)— 35

Method Overloading (III)

Methods(III)— 36

Defining a square method for ints

Defining a square method for doubles

Output confirms that the proper function was called in each case

square of integer 7 is 49square of double 7.5 is 56.25

Method Overloading (IV)

Methods(III)— 37

Common Programming Error Creating overloaded methods with

identical parameter lists and different return types is a syntax error.

Methods(III)— 38

Next Session: Exam

Methods(III)— 39