CSC 153 Grinnell College Spring, 2006
 
Computer Science Fundamentals
 

Supplemental Problems

Quick links: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

Supplemental Problems extend the range of problems considered in the course and help sharpen problem-solving skills. Starred problems 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:  Science Office
        ;;; Supplemental Problem 
    
    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 script 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.

Processing Dates:
  1. A common processing task involves analyzing dates, such as January 8, 2003. For example, one often must determine if a date is the last one in a year or the last one in a month.

    For this problem, dates will have three parts: month day year, where the month and day are integers and the month is a symbol (e.g., january, february, etc.). Write the following procedures:

    Notes:

    1. January, March, May, July, August, October, and December have 31 days.

    2. April, June, September, and November have 30 days.

    3. February has 28 days in non-leap years, but 29 days in leap years. A leap year occurs in years when the year is divisible by 4, except that century years are not leap years unless they are divisible by 400. Thus, the years 1999 and 1900 are not leap years, while 1996 and 2000 are leap years.

    Examples: These procedures should produce the following results:

    
    (year-end? 'march 31 2004)      ===> #f
    (year-end? 'december 30 2004)   ===> #f
    (year-end? 'december 31 2004)   ===> #t
    (month-end? 'january 8 2004)    ===> #f
    (month-end? 'january 31 2004)   ===> #t
    (month-end? 'february 28 2003)  ===> #t
    (month-end? 'feburary 28 2004)  ===> #f
    (month-end? 'february 28 2000)  ===> #f
    
    Note: In this and all other supplemental problems, you may define additional helper functions as you wish. From a user's perspective, the required procedures must be available using the prescribed parameters. Beyond that interface, you may handle processing details in whatever way seems convenient.

Determination of the Following Date:

  1. Programs commonly must determine what date comes after a given one. Write a procedure next-date which returns the date which follows the specified one (e.g., April 1, 1999 follows March 31, 1999). The date returned should be formatted as a list.

    If next-date is given an invalid date as a parameter, it should return an error message rather than a date.

    The following examples illustrate how next-date should work:

    
    (next-date 'january 8 1999)     ===> (january 9 1999)
    (next-date 'february 28 1999)   ===> (march 1 1999)
    (next-date 'february 28 2000)   ===> (february 29 2000)
    (next-date 'february 29 1999)   ===> "invalid date"
    (next-date 'december 31 1999)   ===> (january 1 2000)
    (next-date 'henry 31 2000)      ===> "invalid date"
    

A Racquetball/Volleyball Simulation

  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.

    Hints: Since the flow of activity in this problem is a bit complex, you might try organizing the simulation with several helper procedures.

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. 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 /home/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-city and senators-by-zip-code, in the current working directory. The senators-by-city file should contain the same data as the source file, in the same format (including capitalization), but with the lines arranged alphabetically by city (column 4). 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.

A Simple Class

  1. Computer monitors divide an image into a grip of pixels. Each pixel appears as a colored dot. Pixels are identified by coordinate system, with horizontal and vertical (x and y) coordinates. For example, on a Linux system, the pixel at the upper left of the monitor is given the coordinates (0, 0), and pixel part-way down the screen on the left might have coordinates (0, 300).

    When displaying rectangles (e.g., windows) on a monitor, at least two approaches may be used:

    In this problem, you are to use the second approach. Often, these coordinates are grouped as the upper-left coordinates and lower-right coordinates, but for this introductory problem you should store the four values as separate integer fields.

    Using Java, write a simple Rectangle class with the following properties:

    1. The Rectangle class should have exactly four integer fields for the coordinates of the four sides of a rectangle.
    2. Two constructors should be provided:
      • One constructor should take no parameters, set the upper left corner to (0,0) and set the other coordinates as needed so the rectangle's width will be 800, and the length 600.
      • One constructor should take four parameters −− the four coordinates of the rectangle boundaries.
    3. Four methods, getLeft, getRight, getTop, and getBottom, should return the relevant integer coordinates.
    4. Two methods, setLeft and setTop should allow the user to designate the given coordinate. (In practice, one might check that the coordinates were on the screen. However, such error checking is beyond the scope of the little Java covered so far in the course, and thus is not expected for this assignment.)
    5. A method setWidth that adjusts the coordinate of the right side of the rectangle, so that the rectangle will begin at the designated left side of the rectangle and extend for the width given.
    6. A method setHeight that adjusts the coordinate of the bottom of the rectangle, so that the rectangle will begin at the designated top and extend downward for the given height.
    7. A method computeArea that computes the area of the rectangle.
    8. A method toString that returns a string that gives the coordinates of the rectangle in a readable form.
    9. A method main that provides suitable test cases for the constructors and other methods.

A Gambling Simulation

  1. In private games, different types of gamblers set different personal limits according to the following table:

    Gambler Category Amount at
    Start of Evening
    Amount Bet
    per Game
    Game Payoff Probability of
    Winning Game
    Total to Stop
    Average Gambler $25 $2 $4 0.3 $50
    Low-risk Gambler $10 $1 $1 0.5 $18
    High-risk Gambler $50 $5 $15 0.2 $150

    Interpreting this table, for an average gambler, the gambler starts the evening with $25; 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 specific 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 winning by types of gamblers, 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 PlayGame class that has one method:

      • public String betResult (double prob) that takes a probability as parameter and that uses Java's random number generator to determine if the player wins or loses a specific bet. betResult returns "won" or "lost" according to the corresponding outcome.
    2. Write a Gambler class with these characteristics:

      • The Gambler class has fields for
        
           double betSize;   /* size of each bet */
           double payoff;    /* amount earned (in addition to bet) if bet won */
           double prob;      /* probability of winning a bet */
           double start;     /* amount in gambler's purse at start of evening */
           double purse;     /* current amount gambler holds */
           double quitAmount /* amount gambler must earn before quitting for evening */
        
      • The Gambler class has these methods
        • a constructor, that has parameters for each of the object fields above (except purse which is initialized to start)
        • public String playOneGame (playGame game), that normally places one bet (with the game object), updates the purse field. If the purse is less than betSize or greater than or equal to the quitAmount, then playOneGame retains the current purse without playing. The possible return values are "Won for Evening", "Won Game, Still Playing", "Lost Game, Still Playing" and "Lost for Evening".
        • public String playEvening (playGame game), that starts with the current purse and plays successive games until either the purse is less than betSize or greater than or equal to the quitAmount. The possible return values are "Won for Evening" and "Lost for Evening".
    3. Write 3 subclasses, AverageGambler, LowRiskGambler, and HighRiskGambler, that extend class Gambler by including a constructor with no parameters that set the fields according to the above table.

    4. Write a SimulateGambling class that creates 1000 of each type of Gambler, records how many Gamblers of each type win over a full evening, and prints the results in a table (filling in the question marks below):

      
         Gambler Category    Evenings Won     Evenings Lost
         Average Gambler         ???              ???
         Low-risk Gambler        ???              ???
         High-risk Gambler       ???              ???
      

    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%.

    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, cancellation 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 N between 1 and 1000 from the keyboard and prints the Roman numerals between 1 and N in alphabetical order.

    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 apostrophes 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.

    More Conference Reviewers

    1. Expand Problem 5 as follows:

      Define a Scheme procedure find-reviewers with the following properties

      • the first parameter n contains the number of reviewers desired
      • the second and any subsequent parameters contain names of subject areas
      • the procedure returns a list of names of reviewers, where each individual has as many subject areas as possible in common with the paper.
        • if more than n reviewers have the same number of subject areas in common with the paper, then the procedure may return any n of these.
        • if fewer than n reviewers have any subject areas in common with the paper, then the procedure should return the smaller list of those reviewers with some common areas.

      For example, consider the procedure call

      
      (find-reviewers 5 "Networks" "Databases" "Artificial Intelligence")
      

      Results of this call should be as follows:

      • If the database contains exactly 5 reviewers with all three of these subject areas, then the procedure returns all five names.
      • If the database contains more than 5 reviewers with all three of these subject areas, then the procedure may return any 5 of those names.
      • If the database contains no reviewers with all three subject areas, but 6 reviewers who list two of the areas, then the procedure may return any 5 of those 6.
      • If the database contains 2 reviewers with all three subject areas and 6 reviewers who list two of the areas, then the procedure need return only the first 2.
      • Extra Credit: Supplement the previous example, so that the 2 reviewers with all three subject areas are supplemented by any 3 of the remaining 6.

      Note:

      While this problem specifies the "best" reviewers for a paper, a similar approach might be applied to a roommate-matching program in which potential roommates list various traits and the program finds one or more roommates with the most traits in common. Dating services might use a similar algorithm as well.


    This document is available on the World Wide Web as

    http://www.walker.cs.grinnell.edu/courses/153.sp05/suppl-prob.shtml
    

    created: 6 February 1997
    last revised: 18 February 2006
    Valid HTML 4.01! Valid CSS!