120 likes | 269 Views
Recursion. Alice. Repetition. In some situations, we don’t know exactly how many times a block of instructions should be repeated. All we know is that repetition is needed
E N D
Recursion Alice
Repetition • In some situations, we don’t know exactly how many times a block of instructions should be repeated. • All we know is that repetition is needed • For example, in a board game like chess or checkers, we don’t know exactly how many moves it will take for a player to win or lose the game – all we know is that several moves will be needed.
Indefinite Repetition • In programs where a count of repetitions is not known (indefinite), we can use one of two repetition control mechanisms: • Recursion • While statement • This session focuses on Recursion.
Recursion • Many of the pieces we use to create a program are identified by using special words. For example, • Do in order • Do together • If/Else • Loop • Recursion is not a program statement with a special word that identifies it as part of the programming language. Recursion means that a method (or a function) calls itself.
Example – horse race A carnival style horse race. In repeated moves, one horse is randomly selected to move forward. The selected horse “runs” straight ahead to the finish line. A horse is the winner if it gets to the finish line before any other horse. When one horse wins, the game ends.
Storyboard "do everything again" means that the entire method should be repeated. • To do everything again, the method calls itself. race If one of the horses has won the winner says, “I won!!!” Else randomly choose one horse and move it forward a small amount do everything again
Stepwise Refinement race If one of the horses has won the winner says, “I won!!!” Else randomly choose one horse and move it forward a small amount call race method moveRandomHorseForward whichHorseWon? isGameOver?
Demo • Ch08Lec1HorseRace-V1 • Concepts illustrated in this example • In games, a conditional expression is often used to determine when a game is over. In this example, the game is over when one of the horses gets within 0.5 meters of the finish line. The same condition is used to determine the winner. • Random numbers is used to introduce an element of chance into a game program.
Testing • Testing a program that uses random numbers requires extra caution. • In this example, we ran the program 20 times and found that • racehorse1 won 7 times • racehorse2 won 3 times • racehorse3 won 10 times • Something is wrong! Each horse should win approximately 1/3 of the time.
Demo • Ch07Lec1HorseRace-V2 • The bug in the first version of the program is that it has • nested If statements, and • a 33% probability for each If statement • What we didn't consider is that if racehorse1 was not selected, then we have a 50% probability of selecting either racehorse2 or racehorse3.
Assignment • Read Chapter 8 Section 1, Recursion
Lab • Chapter 8 Lecture 1 Lab