CSC 153 Grinnell College Fall, 2007
 
Computer Science Fundamentals
 

Supplemental Problems

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

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

Format: In turning in solutions to supplemental problems, follow these directions:

  1. The first three lines of any Scheme or Java program should be comments containing your name, your mailbox number, and an identification of assignment being solved. The following lines illustrate this format for Scheme programs.:

    
       ;;; Henry M. Walker
       ;;; Box:  Science Office
       ;;; Supplemental Problem 0
    
  2. Comments are required for every procedure, stating in English what that procedure is supposed to do. The following header illustrates an appropriate format for the square root function:

    
    (define square-root 
       (lambda (number)
       ;;;  pre-condition:  number is a non-negative real number
       ;;; post-condition:  procedure returns the non-negative
       ;;;                  square root of the number parameter
    
  3. Both the Dr. Scheme and Eclipse programming environments provide a mechanism to print a program and to print output from separate windows.

  4. In pen or pencil, annotate your output, so that it is clear what test data produced each result.

  5. For each result, write (in pen or pencil) whether or not the output is correct and how you know. Your argument should be based upon the evidence from the problem (not a tracing of the program).

  6. Include a statement (typewritten, in pencil, or in pen) indicating why your testing covers a reasonable range of cases. That is, explain why your testing allows you to conclude that your program is correct. (If this program were written for a company, your argument should provide adequate proof that you should be paid for your work, based on the problem assigned.)

  7. In addition to turning in your program in paper form, e-mail your program file(s) to walker@cs.grinnell.edu The subject line of your e-mail should be:

    
    CSC 153 Supplemental Problem [number]
    
    where [number] is the problem number.
Note: It is essential that each supplemental problem follows the specified directions.

Deadlines:


Ranking a Conference Paper
  1. It is common for researchers to submit papers to professional conferences. These papers then are sent to reviewers, who assign an overall rating to each paper.

    For one conference, a reviewer rating is an integer between 1 and 6 inclusive, and each paper typically is reviewed by 4 — 6 reviewers. Based on these ratings, each paper is placed in a preliminary category according to the following scale:

    Write a procedure determine-category that takes a non-empty list of reviewer ratings as parameter and returns the preliminary category as a string, based on the above scale.

    Notes:

Computing a Polynomial

  1. A polynomial function has the form

    p(x) = anxn + an-1xn-1 + ... + a2x2 + a1x + a0

    Write a procedure compute-poly that takes two parameters:

    and returns the value of the polynomial p(x).

    Notes:

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.

    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.

Generating Mail-Merge Letters

  1. A common application of computers involves sending "personalized" form letters to a list of individuals. This problem demonstrates a relatively simple version of this program. The application utilizes three input files:

    We consider each of these in turn.

    1. One file contains a list of names and associated addresses. For this problem, we will assume that the first line of an entry for an individual contains the individual's name. Subsequent lines contain the address, and each individual's entry ends with a blank line. For example, a name/address file with three names might be:

      
      Dean Jim Swartz
      Nollen House
      Grinnell College
      Grinnell, IA  50112
      
      Muffin (the Cat)
      1432 Summer Street
      Grinnell, IA  50112
      
      Henry M. Walker
      Department of Computer Science
      Grinnell College
      Noyce Science Center
      1116 Eighth Avenue
      Grinnell, IA  50112
      

      Although the name always involves exactly one line, addresses may contain one, two, or more lines. Within the file, exactly one blank line (with just a return character) separates an address from the next entry. Also, the file ends with exactly one blank line (ending the previous entry).

    2. The template file contains the letter being sent to each individual. An individual's letter contains exactly the text in this template, except that "personalized" information is substituted for certain keywords. All keywords start with two dollar signs $$. Three specific keywords are shown in the following table:

      $$name the first line of an individual's entry within the name/address file
      $$address the second and subsequent lines of an individual's entry
      $$entry the entire entry of an individual within the name/address file, including both the name and address
    3. The alias file contains a list of keywords and their substitutions, with one keyword/substitution per line. Each line starts with a keyword, followed by a space character. The substitution for the keyword starts immediately after the space character. Here is a sample alias file that defines five keywords:

      
      $$todaysdate October 10, 2007
      $$organization Computer Science Club
      $$event Annual Fall Picnic
      $$when Friday, October 26, 2007
      $$where Merrill Park
      

    With this framework, generation of letters proceeds by reading the template letter for each individual in the name/address file, creating an output file that can be printed (eventually). For each individual, the letter is created, substituting substitutions for each keyword. For example, suppose the template file consists of the following:

    
         $$todaysdate
         $$entry
    
         Dear $$name,
    
         You are invited to the $$event,
         to be held at $$where on $$when.
    
         See you then!
    
         $$organization
    

    With this template, the above name/address file, and the above keywords, the second letter generated would be:

    
         October 10, 2007
         Muffin (the Cat)
         1432 Summer Street
         Grinnell, IA  50112
    
         Dear Muffin (the Cat),
    
         You are invited to the Annual Fall Picnic,
         to be held at Merrill Park on Friday, October 26, 2007.
    
         See you then!
    
         Computer Science Club
    

    Write a procedure create-letters that takes four parameters (a name/address file, the template file, the alias file, and an output file) and generates letters for each name/address, based on the template file and aliases.

    After finishing one letter, print a "form feed" character to the output before starting the next letter. When sent to a printer, this will ensure that each letter starts on a new page.

Points and Rectangles

  1. Many graphical applications start with the concept of points and then combine points into rectangles. This problem considers simple elements of both of these objects.

    1. Write a class Point with the following properties:
      • The class Point should have two integer fields, x and y
      • Two constructors
        • One with no parameters should set the point to the origin (0, 0)
        • One with two parameters — the x and y coordinates, respectively.
      • Two methods, getX and getY, should return those values, respectively.
      • Two methods, setX and setY, should set the relevant value.
      • A method toString that returns a string that gives the coordinates of the point as an ordered pair surrounded by parentheses , such as "(37, 52)".
      • A method main that provides suitable test cases for the constructors and other methods.
    2. Write a class Rectangle that will represent a box with sizes parallel to the x and y axes; we will assume that all rectanges are in the first quadrant (so the origin is to the lower left of the rectangle). This class should have the following properties:

      • The class Rectangle should have exactly two elements of class Point as its fields, where one point gives the coordinates of the upper-left corner of the rectangle and the other point gives the coordinates of the lower-right corner of the rectangle.
      • Two constructors
        • One should take no parameters, set the upper left corner to (0, 0) and set the other coordinates so the rectangle's width will be 800, and the length 600.
        • One should take four parameters — the four coordinates of the rectangle boundaries.
      • Four methods, getLeft, getRight, getTop, and getBottom, should return the relevant integer coordinates.
      • Two methods, setLeft and setTop should allow the user to designate the given coordinate. (In practice, one might check that the coordinates were in the first quadrant. 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.)
      • 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.
      • 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.
      • A method computeArea that computes the area of the rectangle.
      • A method toString that returns a string that gives the coordinates of the rectangle in a readable form.
      • A method main that provides suitable test cases for the constructors and other methods.

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.

    This supplemental problem asks you to create a Password class with the following elements:

    1. a String field that is declared as private,
    2. a (public) setPassword method that sets the object's local field to a designated password.
    3. a local (private) method isVowel that has a single parameter (of type char) and returns true if the parameter's value is a vowel and false otherwise.
    4. a local (private) method isConsonant has a single char parameter and returns true if the parameter's value is a consonant and false otherwise.
    5. a local (private) method isPunctuation has a single char parameter and returns true if the paramter's value is a punctuation mark (i.e., not a letter or digit) and false otherwise.
    6. a local (private) method boolTo01 that has a single boolean parameter and returns 1 if the parameter's value is true and 0 otherwise.
    7. a (public) method containsUpperCase that returns true if the object's local String field contains an upper case letter and false otherwise.
    8. a (public) method containsLowerCase that returns true if the object's local String field contains a lower case letter and false otherwise
    9. a (public) method containsDigit that returns true if the object's local String field contains a digit character and false otherwise.
    10. a (public) method containsPunctuation that returns true if the object's localString field contains a character of punctuation and false otherwise.
    11. a (public) method passwordGrade that returns a char grade for the object's local field 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.

    Hint: Java's Character class may have built-in methods that are useful for testing several various categories of characters.

Simulation of Hi Ho! Cherry-O

  1. This problem explores statistics for the game of Hi Ho! Cherry-O. For our purposes, we will follow the description of the game as described in Wikipedia. Note, however, that the number of cherries on a player's tree is always between 0 and 10. If one spins a bird or dog and the number of cherries on the tree is 8 or fewer, then the number of cherries on the tree goes up by 2. However, if one spins a bird or dog and the number of cherries on the tree is 9 or 10, then the number of cherries on the tree goes to 10 (not higher).

    The game progresses in rounds, during which each player in turn spins a game spinner that has seven outcomes (as described in the Wikipedia article). In our simulations, we will assume that each outcome of the spinner arises randomly with equal probability.

    Within this framework, the specific purpose of this supplemental problem is general statistics on how many rounds the game is likely to continue, based on the number of people playing the game. The first step is to write a class Player that follows the game board for an individual player. In particular, Player has one private int field and three methods, as follows:

    The actual Hi Ho! Cherry-O game proceeds with 2 to 4 players, each taking a turn in sequence until someone wins. For any individual player, it would seem possible that the player would pick a few cherries, but then have the number on the tree go back up by spinning a bird, dog, or spilled bucket. If turns alternate between picking cherries and putting some back, the game could go on indefinitely. As the number of players increases, one might expect that the likelihood will decrease that all players encounter a long, indefinite sequence. That is, one might expect that the average number of rounds in a game will decrease. Class SimulateGames runs many games with various number of players to explore some statistics of these games. In particular, SimulateGames has these fields and methods.

    In testing this program, try several test runs with the insertion sort algorithm, and use a clock's second hand to approximate how much tiime each run takes. Then, switch the program to use the quicksort in place of the insertion sort, and again time how long each run takes. In your discussion of program correctness, indicate average run times for each sorting algorithm, and indicate your conclusion about the impact of the two sorting algorithms on the overall processing.

A Recipe Collection

  1. An individual plans to maintain a list of recipes within a program. Although a production-level program likely would keep track of many details, the data for this problem are relatively straightforward:

    This framework for recipes can be modeled with a Recipe and three subclasses: Drink, Vegetable, and Dessert. In addition to a Constructor method, each class will need a toString method that formats the information for each type of recipe. Each class also should have appropriate methods to change each field.

    For this problem, these recipes will be stored on a linked list with these features:

    In addition to the Recipe class and its subclasses, implement a linked list RecipeCollection class as described. If it will be helpful, you may also implement a ListNode class, following the discussion of lists in the Lists in Java lab.

    At this point in the semester, it should go without saying that all code should be well documented, logically formatted, and appropriately tested, with a reasonable discussion of why the code is correct.


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

The Middle of a List

  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, as follows:

    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 4) ===> ()
    (list-middle '(a b c d e f g) 5 0) ===> (f g)
    (list-middle '(a b c d e f g) 2 -2) ===> (c d e)
    (list-middle '(a b c d e f g) 0 7) ===> error
    (list-middle '(a b c d e f g) -1 4) ===> error
    

Fibonacci Numbers

  1. In mathematics, the Fibonacci sequence is a sequence of positive integers, as follows.

    Thus, the first 10 elements of the Fibonacci sequence are: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

    Write and test a tail-recursive Scheme procedure Fibonacci which takes a parameter n and returns the nth Fibonacci element in the sequence. Also, write a test a procedure Fib-seq which takes a parameter n and returns a list containing the first n elements of the Fibonacci sequence.

    
    (Fibonacci 10)  ===> 55
    (Fib-seq 10)    ===> (55 34 21 13 8 5 3 2 1 1)
    

Checking Pairs of List Elements

  1. A list of numbers in ascending order has the property that each pair of numbers on the list (e.g., (n m)) satisfies the < relation (e.g., (< n m) is true). Similarly, each successive pair of numbers is a descending list of numbers satisfies the > relation. For a list of strings in ascending alphabetical order, the relevant relationship for successive pairs of list items is string-ci<=?. Etc. This problem asks you to write a higher-order Scheme procedure to generalize this checking of list items.

    Write a procedure check-list-pairs that has a predicate pred? as parameter and that returns a procedure. The returned procedure has a list lst as parameter and returns true if pred? is true for each successive pair of items on lst and false otherwise.

    Here are several examples:

    
    (define ascending? (check-list-pairs <))
    (define descending? (check-list-pairs >))
    
    (ascending? '(-50 0 50 100 150)) ===> #t
    (ascending? '(150 100 50 0 -50)) ===> #f
    (ascending? '(3 1 4 1 5 9 2)) ===> #f
    (ascending? '(1 2 3 5 8 13))  ===> #t
    (ascending? '(-5000)) ===> #t
    
    (descending? '(150 100 50 0 -50)) ===> #t
    (descending? '(5.0 4.1 3.8)) ===> #t
    (descending? '(8 7 6 4 5 3 2 1)) ===> #f
    (descending? '(0 0 0 0)) ===> #f
    (descending? '(-3 -2)) ===> #f
    (descending? '(17)) ===> #t
    
    

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.

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

More Conference Reviewers

  1. Expand Problem 14 as follows:

    Define a Scheme procedure find-reviewers with the following properties

    For example, consider the procedure call

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

    Results of this call should be as follows:

    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.fa07/suppl-prob.shtml

created created 5 February 1997
last revised 3 November 2007
Valid HTML 4.01! Valid CSS!