How to Design Programs: An Introduction to Programming and Computing

Info icon This preview shows pages 1–3. Sign up to view the full content.

How to Design Programs: An Introduction to Computing and Programming [Go to first , previous , next page; contents ; index ] Section 37 Examples of Memory Usage Designing programs with memory requires experience and practice, which, in turn, come from studying examples. In this section we study three more examples of programs that use memory. The first one illustrates the importance of initializers; the second one demonstrates how to design programs whose effects depend on conditions; and the last one shows how effects can be useful in recursive functions. The last two subsections provide opportunities for practicing what we've learned. 37.1 Initializing State Recall the color-guessing game from exercise 5.1.5 . One player picks two colors for two squares; we call those ``targets.'' The other one tries to guess which color is assigned to which square; they are guesses. The first player's response to a guess is to compare the colors and to produce one of the following answers: 1. 'perfect! , if the first target is equal to the first guess and the second target is equal to the second guess; 2. 'OneColorAtCorrectPosition , if the first guess is equal to the first target or the second guess is equal to the second target; 3. 'OneColorOccurs , if either of the guesses is one of the two targets; 4. and 'NothingCorrect , otherwise. These four answers are the only answers that the first player gives. The second player is to guess the two chosen target colors in as few guesses as possible. To simplify the game, the choice of colors is limited: see the top of figure 102 . Our goal is to develop a program that plays the role of the master player. That is, we want a program that picks the colors and checks the guesses of the second player. (1 of 22) [2/5/2008 4:57:43 PM]
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.