CSC 153 Grinnell College Spring, 2005
 
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.

Computing a Babysitter's Fee:
  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 Scheme program that has four integer parameters (the sitter's starting time in hours and minutes and the ending time in hours and minutes) and computes the sitter's fee. Assume all times are between 6:00 pm and 6:00 am, and hours should be entered as being between 0 and 12 (inclusive). Hours outside the range of 0 to 12 should be considered invalid.

    The following table may clarify allowed time values for this problem.

    Starting Starting Ending Ending StartingEnding
    Hour Minutes Hour Minutes Time time
    8 0 3 30 8:00pm 3:30am
    6 0 0 45 6:00pm 12:45am
    12 0 6 0 12:00am (midnight) 6:00am

    Programming Note: You may NOT use any if statements, loops, or recursion in your procedure(s) for this program. Rather, you ARE encouraged to use cond statements to handle the parallel conditions that arise in this problem.

List-Middle

  1. Write and test a Scheme procedure list-middle that takes three parameters (a list ls, an integer first, and an integer last) and returns a list of the elements of ls, starting with the element with index first and concluding with the element with index last.

    Notes:

    
    (list-middle '(0 1 2 3 4 5 6) 2 5) ===> (2 3 4 5)
    (list-middle '(a b c d e f g) 2 5) ===> (c d e f)
    (list-middle '(a b c d e f g) 0 6) ===> (a b c d e f g)
    (list-middle '(a b c d e f g) 6 0) ===> ()
    (list-middle '(a b c d e f g) 0 7) ===> error
    (list-middle '(a b c d e f g) -1 4) ===> error
    

Grading Passwords

  1. Since many modern computer systems use passwords as a means to provide protection and security for users, a major issue can be the identification of appropriate passwords. The main point should be to choose passwords that are not easily guessed, but which the user has a chance of remembering. For example, passwords related to birthdays, anniversaries, family names, or common words are all easily guessed and should be avoided.

    Some common guidelines suggest that a password should contain at least 6 characters and include characters from at least three of the following categories:

    Other guidelines indicate that elements of passwords should be pronounceable. One simple measure of this guideline suggests that any group of letters in a password should contain both vowels and consonants.

    In Scheme, some procedures are already built-in to test some of these conditions. Specifically, the Scheme standard identifies the procedures char-alphabetic?, char-numeric?, char-whitespace?, char-upper-case?, and char-lower-case?. See the section on characters in the Scheme standard for more details.

    1. The first part of this supplemental problem is to write additional procedures for other categories of characters. (Some of these procedures were part of the lab on characters and may be reused.)

      • Procedure vowel? has a single parameter and returns true if the parameter's value is a vowel and false otherwise.
      • Procedure consonant? has a single parameter and returns true if the parameter's value is a consonant and false otherwise.
      • Procedure punctuation? has a simple parameter and returns true if the parameter's value is a punctuation mark (i.e., not a letter or digit) and false otherwise.


      Note: While you are free to use built-in Scheme predicates for these procedures, you may not use type conversion procedures. Thus, you are not allowed to convert characters to integers or other data types.

    2. The second part of this problem is to write a tail-recursive procedure that checks whether a string contains a character meeting a particular test. Specifically, write procedure
      
         (contains? str pred?)
      

      which applies the predicate pred? to each character in string str and which returns 1 if some character meets this predicate test and 0 otherwise. For example, contains? should return the following results:

      
      (contains "Walker" char-upper-case?) ===> 1
      (contains "Walker" char-lower-case?) ===> 1
      (contains "Walker" char-numeric?)    ===> 0
      (contains "Walker" punctuation?)     ===> 0
      


      Note: To meet the specifications below, contains? must return 1 or 0, not #t, #f, or another number.

      Also note: If you can, this procedure should handle strings as strings, rather than converting a string to another data type such as a list.

    3. The third part of this problem is to write procedure password-grade which takes a string as parameter and which gives a grade to that password according to the following grading scale:
      • Assign 1 point for each of the following elements in the password:
        • password contains at least 6 characters
        • password contains at least 1 vowel
        • password contains at least 1 consonant
        • password contains at least 1 upper-case letter
        • password contains at least 1 lower-case letter
        • password contains at least 1 numeric character
        • password contains at least 1 punctuation mark


      • Assign a letter grade to the password by applying the sum of the points above to the following.
        • 6 or 7 points: A
        • 5 points: B
        • 4 points: C
        • 3 points: D
        • 0 or 1 or 2 points: F

    According to this scale, "Walker" would receive a "B" grade, with points for string length, vowel, consonant, upper-case letter, and lower-case letter.

    After writing and debugging your procedures, use the script process described at the beginning of these supplemental problems to turn in your code. In considering the correctness of your code, be sure to write out (in a paragraph) what cases each procedure might encounter, identify test cases to cover each of those cases, show the testing in your script file, and comment on the extent to which your code handles those cases correctly.

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                 −−      −−      −−
    

Conference Reviewers

  1. For many professional conferences, authors submit papers on their research. These papers are then sent to reviewers for comments, and the best papers are selected for presentation. A similar process is used for determining papers to appear in journals. This problem considers how reviewers might be selected.

    For a computer-related conference, organizers maintain a database of reviewers, together with a list of the subject areas these reviewers feel competent to judge. One possible structure for this database is a list of lists. File /home/walker/151s/labs/reviewer-directory.ss defines Scheme variable directory that contains a ficticious version of such a database. The first part of this list of lists is:

    
    (define directory
     '(("Terry Clark" "Networks" "Distributed Systems" "Distributed Systems")
       ("Carol Walker" "Cryptography" "Software Design" "Multimedia"
             "Algorithms")
       ("John McClelland" "Software Design" "Distributed Systems" "Networks"
             "Ethical/Social Issues" "Theory of Computation" "Algorithms")
       ("Lisa Dale" "Networks" "Distributed Systems" "Theory of Computation"
              "Ethical/Social Issues")
       ("Arnold Freeman" "Operating Systems" "Databases" "Networks"
              "Distributed Systems" "Architecture")
       ("Terry Barnes" "Networks" "Artificial Intelligence" "Cryptography"
             "Architecture")
    ...
      )
    )
    

    This entire list of lists may be loaded within a Scheme program with the statement:

    
    (load "/home/walker/151s/labs/reviewer-directory.ss")
    

    When a paper is submitted to the conference, the author specifies several related subject areas. In order to facilitate reviewing, the conference organizers wish to find reviewers whose expertise as many of the author-designated subject areas as possible.

    Problem

    Define a Scheme procedure find-all-reviewers with the following properties

    To be on the resulting list of reviewers, an individual may have many interests beyond those indicated for the paper -- as long as the paper's topics are all covered.

A Simple Rectangle 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 follwing 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 $5 0.4 $50
    Low-risk Gambler $10 $1 $1 0.5 $18
    High-risk Gambler $50 $5 $15 0.3 $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 /* amout 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 normaly 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 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.

    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.cs.grinnell.edu/~walker/courses/153.sp05/suppl-prob.shtml
    

    created created February 6, 1997
    last revised March 3, 2005
    Valid HTML 4.01! Valid CSS!