Supplemental Problems For Computer Science 151

Supplemental Problems

Supplemental Problems

Problems: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14

Supplemental Problems extend the range of problems considered in the course and help sharpen problem-solving skills. Problems number 8 or higher may be turned in for extra credit.

Format: In turning in any programs for the course, please follow these directions:

  1. The first three lines of any Scheme program should be comments containing your name, your mailbox number, and an identification of assignment being solved. For example:
    
        ;;; Henry M. Walker
        ;;; Box Y-06
        ;;; Supplemental Problem 2
    
    Also, a comment is needed for every procedure, stating in English what that procedure is supposed to do.

  2. Obtain a listing of your program and a record of relevant test runs using the submit command:

  3. Either write on your printout or include a separate statement that argues why your program is correct, based upon the evidence from your test runs.
List Processing: A common processing pattern in Scheme involves operating on pairs of adjacent elements in a list rather than on single elements. For instance, we might want a procedure adjacent-sums that takes a non-empty list of numbers and returns a list of the sums of adjacent pairs, thus:

(adjacent-sums '(1 2 3 4 5 6 7)) ===> (3 5 7 9 11 13)
(adjacent-sums '(-5 12 13 0 -8)) ===> (7 25 13 -8)
(adjacent-sums '(7/3 -1/2 8/5 9/4)) ===> (11/6 11/10 77/20)
(adjacent-sums '(4 7)) ===> (11)
(adjacent-sums '(16)) ===> ()
Here's how we'd write it:

(define adjacent-sums
  (lambda (ls)
    (if (null? (cdr ls))
        '()
        (cons (+ (car ls) (cadr ls)) (adjacent-sums (cdr ls)))
     )
   )
)
  1. Give your own rendition of this procedure ``in English.''

  2. Write and test a Scheme procedure adjacent-elements that takes any non-empty list ls and returns a list of two-element lists, each two-element list consisting of two adjacent elements of ls.
    
    (adjacent-elements '(a b c d e)) ===> ((a b) (b c) (c d) (d e))
    (adjacent-elements '(5 12 12 0)) ===> ((5 12) (12 12) (12 0))
    (adjacent-elements '(first second)) ===> ((first second))
    (adjacent-elements '(only)) ===> ()
    
  3. Write and test a Scheme predicate (a procedure that always returns #t or #f) that takes any non-empty list of real numbers and determines whether they are in ascending numerical order, in the sense that each one is strictly less than the one that follows it.
    
    (ascending? '(-50 0 50 100 150)) ===> #t
    (ascending? '(3.8 4.1 5.0)) ===> #t
    (ascending? '(1 2 3 5 4 6 7 8)) ===> #f
    (ascending? '(0 0 0 0)) ===> #f
    (ascending? '(-2 -3)) ===> #f
    (ascending? '(17)) ===> #t
    
Another Exercise
  1. A baby sitter charges $1.50 per hour until 9:00 pm (while the kids are still up), $1.00 per hour between 9:00 pm and midnight, and $1.25 per hour after midnight (since late night baby sitting interferes with morning classes).

    Write a procedure that takes as arguments the sitter's starting time in hours and minutes and the ending time in hours and minutes and then computes the sitter's fee. Assume all times are between 6:00 pm and 6:00 am; hours should be entered as numbers on a 12-hour clock, so that hour 3 should be considered as 3:00 am and hour 8 should be considered as 8:00 pm. Hours outside the range 0 to 12 should be considered invalid.

A Gambling Simulation
  1. In a private game, a gambler sets the following personal limits. The gambler starts the evening with $20; he bets $2 on each game and stops when he either runs out of money or has a total of $50. To be more specific, for a specifc game, the gambler bets $2. If the gambler loses the bet, then $2 is deducted from his account. If the gambler wins the bet, then the gambler wins a payoff amount, and the gambler's new balance is increased by that payoff -- the $2 is not deducted. For example, if the payoff is $5 and if the gambler starts the game with $20, then the gambler's new balance would be $18 if the gambler loses a bet and $25 if the gambler wins the bet.

    The following problems will allow you to investigate the likelihood of the gambler winning by simulating games each evening over a period of 1000 nights of gambling. To accomplish this simulation, you are to proceed in three steps:

    1. Write a procedure game which simulates a single bet. Thus, game should have parameters for the gambler's purse amount before the bet, the payoff from a $2 bet, and the probability of the gambler winning the single bet. Then game should return the amount the gambler has after that single bet, using a random number generator and the probability to determine if the gambler won. For example,
      
         (game  37  5  0.7)
      
      should represent the result of a bet, when the gambler starts with $37, when the return on a $2 bet is $5, and when the gambler has a 70% chance of winning the bet. With these values, game should return 35 if the gambler loses the bet and 42 if the gambler wins.

      Note that one way to simulate a bet is to compare (random 1.0) with the probability 0.7:

      
         (cond ((< (random 1.0) 0.7) ;winning part
                    )
               (else ;losing part
                    )
          )
      
    2. Modify game to obtain a procedure evening as follows:
      • the gambler always begins an evening with a $20 purse.
      • if the gambler is cleaned out (the balance is less than $2, the amount required for another bet), evening should return "lost";
      • if the gambler's balance is $50 or more, evening should return "won";
      • if the gambler is still playing and wins the current bet, the gambler continues playing, with the winnings added to his purse; and
      • if the gambler is still playing and loses a bet, then gambler continues playing, with the $2 bet deducted.

      For example, the call

      
         (evening  5  0.7)
      
      should simulate an evening of gambling, where the balance begins at $20, the payoff amount is $5, and the probability of winning a game is 0.7 . The result of this call will be the conclusion "won" or "lost".

    3. Using evening, write a procedure simulate-evenings which takes the payoff from a $2 bet, the probability of winning a single bet, and a number of evenings to be played as parameters and returns the number of evenings won. For example, if the gambler consistently plays (fair) games which have a $2 payoff and a 50% chance of winning, and if the gambler plays 1000 evenings of gambling, then an appropriate procedure call would be:
      
         (simulate-evenings  2  0.5  1000)
      
      Similarly, if the gambler consistently plays (fair) games which have a $4 payoff and a 1/3 change of winning, and if the gambler plays 500 eveings of gambling, then an appropriate procedure call would be:
      
         (simulate-evenings  4  1/3  500)
      
      Hint: Since the number of evenings to be played is the new element distinguishing simulate-evenings from evening, you might focus upon that parameter as the basis for processing in simulate-evenings. An appropriate call to the evening procedure already will handle other details of betting for an evening.

    4. After you have written your procedures, be sure to test them in several cases. What test cases and results can help you determine that your code might be correct?

Reading From A File
  1. This exercise, adapted from a problem by John David Stone, is to write a Scheme program, containing definitions for one or more Scheme procedures, that compares the average earnings of American production workers with the costs of basic goods and services in several recent years, leading to an answer to the question, ``In which of those years was the purchasing power of a typical production worker at its highest level, and in which was it at its lowest level?''

    Here is a short table containing the relevant data. Each row contains information about a particular year, which is identified in the first column. The second column shows the average weekly earnings, in dollars, of production workers (including mining, manufacturing, and construction workers and non-supervisory workers in transportation, public utilities, wholesale and retail trade, finance, insurance, real estate, and service industries). The third column in each row gives the annual average Consumer Price Index (CPI), a measure of the prices of such basic goods and services as food, clothing, shelter, fuel, transportation fares, medical treatment, and prescription drugs. The CPI is not measured in dollars, but as a percentage of the prices of the same selection of goods and services in some ``base period,'' currently 1982-1984.

    1970 $119.83 38.8
    1975 $163.53 53.8
    1980 $235.10 82.4
    1985 $299.09 107.6
    1987 $312.50 113.6
    1988 $322.02 118.3
    1989 $334.24 124.0
    1990 $345.35 130.7
    1991 $353.90 136.2
    1992 $363.61 140.3
    1993 $373.64 144.5
    1994 $386.21 148.2
    1995 $393.99 152.4
    1996 $405.92 156.9
    1997 $416.84 160.5

    (The source for these data is the Bureau of Labor Statistics of the United States Department of Labor.)

    These data are stored in /home/walker/151s/labs/labor-statistics.dat . The first two lines of this file contain title information. Thereafter, the data for each year are given on a separate line.

    The ratio between a person's weekly earnings and the Consumer Price Index is a rough indication of the person's ability to afford essential goods and services: When this ratio increases, a person can afford them more easily; when it decreases, less easily.

    Write a Scheme program which reads the data from this file and determines the years, from among those listed, in which the maximum and minimum values of the ratio just described were reached, and what those maximum and minimum values were.

Reading Test Data

  1. File test.data in directory ~walker/151s/labs contains information on test results for a certain class. Each line of the file contains a students first and last name and the results of three hour tests. (The first and last names always are separated by exactly 1 space character, and there always are at least two space characters after the last name before the first test score apears.)

    Write a program that computes the average test score for each student, the maximum and the minimum scores for each test, and prints the results in a nicely formatted table. For example, the table might have the following form:

    
         Name                        Test
    First        Last        1       2       3     Average
    Egbert       Bacon      88      85      92      88.33   
    .
    .
    .
    Maximum                 --      --      --
    Minimum                 --      --      --
    
Information on the 1997-1998 Iowa Senate

  1. File /u2/walker/151s/labs/ia-senate contains information about the members of the 1997-1998 Iowa Senate. After a title line and a blank line, a typical line has the following form:
    
    Angelo          Jeff        44      Creston           IA 50801
    Kramer          Mary        37      West Des Moines   IA 50265
    Lundby          Mary        26      Marion            IA 52302-0563
    
    Thus, a typical line gives the last name, the first name, the district number, the town of residence, the state (always IA), and the town's zip code. The information in these lines is arranged in columns.

    Design and write a Scheme program that reads in data from this file and creates two output files, senators-by-district and senators-by-zip-code, in the current working directory. The senators-by-district file should contain the same data as the source file, in the same format, but with the lines arranged by senate district (column 3). The other file, senators-by-zip-code, should contain a list of all senators in the following format

    
    Jeff Angelo
    Creston, IA 50801
    
    A blank line should appear after each senator and city address. In this format, the name appears on a first line (first name, then last), and the city, a comma, the state, and zip code is on the next line -- separated by single spaces in the format shown. Note that a variation of this format (with a street address, if available) might be used for a mailing label.


Any of the following problems may be done for extra credit. As noted in the course syllabus, however, a student's overall problems' average may not exceed 120%.

Multiplication of Three-Digit Integers

  1. Write a procedure that has two three-digit integers as parameters and then prints their product in the following format:
    
            749
        x   381
        -------
            749
          5992
         2247
        -------
         285369
    
Unusual Canceling
  1. The fraction 64/16 has the unusual property that its reduced value of 4 may be obtained by "canceling" the 6 in the numerator with that in the denominator. Write a program to find the other fractions whose numerators and denominators are two-digit numbers and whose values remain unchanged after "canceling."

    Of course, some fractions trivially have this property. For example, when numerator and denominator are multiples of 10, such as 20/30, one can always "cancel" the zeroes. Similarly, cancelation is always possible when the numerator and denominator are equal, as in 22/22. Your program should omit these obvious cases.

Roman Numerals
  1. Write a procedure that reads an integer between 1 and 1000 from the keyboard and prints the equivalent number in Roman numerals.

Game Simulation Exercise
  1. This exercise involves the completion of one of the following problems:

  1. Racquetball: Racquetball is a game played by two players on an indoor, enclosed court. Scoring proceeds as follows:
    • The score starts at 0 - 0.
    • Player A starts serving.
      • When Player A wins a volley, she scores a point and is allowed to serve again.
      • When Player A loses a volley, she loses the serve but no points are scored.
    • Player B starts serving.
      • When Player B wins a volley, she scores a point and is allowed to serve again.
      • When Player B loses a volley, she loses the serve but no points are scored.

    A player can only score points while she has the serve. A player loses the serve when she loses a volley, but no points are scored on the change of serve. Play continues until either the score is 11-0, which is a shut-out, or one player scores 21 points. (The rules do not require a player to win by two points.)

    Write a program that reads the probability of Player A winning a volley and then simulates the playing of 500 games with Player A having the first serve on each game. Record the number of wins (including shut-outs) for each player and the percentage of wins. Also record the number of shut-outs for each player.

  2. Volleyball:Volleyball is a game played on a court by two teams, separated by a net. Scoring proceeds much the same way as in racquetball (as explained above). In particular, scoring starts at 0-0. A team can only score points while it serves. A team loses the serve when it loses a volley, but no points are scored on the change of serve. Play continues until one team scores 15 points, and a team must win by at least two points (if the score is 15-14, play must continue until one team leads by 2 points). There is no special rule for ending a game due to a shut-out.

    Write a procedure that has as parameter the probability of Team A winning a volley and then simulates the playing of 500 games with Team A having the first serve on each game. The procedure should print the number of wins for each team and the percentage of wins. The procedure also should print the number of shut-outs for each team.

    Hint: Since the flow of activity in this problem is a bit complex, you might write an initial outline describing the overall flow of work for the simulation and/or within a game. Then write main procedures which follow this overall structure and which call other procedures to handle specific details. For example, an overall simulation procedure for the entire 500 games might call an individual game procedure to find the result of each game. The overall simulation procedure then would only have to tabulate results -- the individual game procedure would handle details of a game.

City Data

  1. The file ~walker/151p/labs/lab26.dat contains several items of information about large American cities. More specifically, in ~walker/151p/labs/lab26.dat , each entry consists of the name of the city (line 1), the county or counties (line 2) and the state (line 3) in which it is situated, the year in which it was incorporated (line 4), its population as determined by the census of 1980 (line 5), its area in square kilometers (line 6), an estimate of the number of telephones in the city (line 7), and the number of radio stations (line 8) and television stations (line 9) serving the city. Thus a typical entry reads as follows:
    
    Albuquerque
    Bernalillo
    New Mexico
    1891
    331767
    247
    323935
    14
    5
    
    A blank line follows each entry, including the last.

    Write a procedure which has a filename as parameter and which answers the following questions about the cities represented in the data files.

    1. Which of those cities has the highest population density (population divided by area)?
    2. Which of these cities has over one million telephones?
    3. Which city has the lowest per capita number of radio and television stations (together)?
    The answers to each of these questions should be printed neatly and clearly by the procedure.

File Analysis

  1. Write a procedure file-analysis that takes the name of a file as its argument, opens the file, reads through it to determine the number of words in each sentence, displays the total number of words and sentences, and computes the average number of words per sentence. The results should be printed in a table (at standard output), such as shown below:
    
         This program counts words and sentences in file "comp.text ".
    
         Sentence:  1    Words: 29
         Sentence:  2    Words: 41
         Sentence:  3    Words: 16
         Sentence:  4    Words: 22
         Sentence:  5    Words: 44
         Sentence:  6    Words: 14
         Sentence:  7    Words: 32
    
         File "comp.text" contains 198 words words in 7 sentences
         for an average of 28.3 words per sentence.
    
    In this program, you should count a word as any contiguous sequence of letters, and apostrophies should be ignored. Thus, "word", "sentence", "O'Henry", "government's", and "friends'" should each be considered as one word.

    Also in the program, you should think of a sentence as any sequence of words that ends with a period, exclamation point, or question mark.
    Exception: A period after a single capital letter (e.g., an initial) or embedded within digits (e.g., a real number) should not be counted as being the end of a sentence.
    White space, digits, and other punctuation should be ignored.



This document is available on the World Wide Web as

http://www.math.grin.edu/~walker/courses/151/suppl-prob.html

created February 6, 1997
last revised November 9, 1998