CSC 207 Grinnell College Spring, 2012
 
Algorithms and Object-Oriented Design
 

Supplemental Problems

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

Quick links: 1, 2, 3, 4

Format:

In turning in any programs for the course, please submit the following materials, in the order specified (so the program with you name and box will be on top).

Electronic copy of programs is not needed — do not send email with a copy of your code!

  1. Print and submit a paper copy of each Java class (copying and pasting from Eclipse is ok)

  2. Include within your code javadoc documentation for

    In particular, print and submit the javadoc documentation for your files.

  3. A printed copy of relevant test runs (copying and pasting ok)

  4. A separate statement (typed or handwritten) indicating why the testing indicates the code may be correct. For example, the following questions should be addressed:

Some Grading Notes:


A Simple Class

  1. Computer monitors divide an image into a grid 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       ???              ???
      

Multiple Clerks in a Store

  1. Consider a commercial environment where multiple clerks are available to serve customers. There are at least two models for such service:

    These two models are illustrated schematically in the following diagram.

    One- and Multiple-Queues in a Store

    Discussion

    The following comments are based on the discussion of Problem 17.7, "Checkout Line Waiting Times", found in Henry M. Walker, Introduction to Computing and Computer Science with Pascal, Little, Brown, and Company, 1986, pp. 545-549 and used with permission of the copyright holder.

    This problem, and variations of it, involve considerable complexity, and their solutions have important implications for managers, since companies will lose business if customers become discouraged due to long lines. On the other hand, large numbers of clerks can keep waiting times short, but these clerks must be paid. Thus, a balance is needed between customer waiting times and the number of clerks hired.

    Suppose we are given the average number of people needing service and the average service time. It seems unrealistic to assume that these people enter the line at a uniform rate or that the service always requires exactly the same amount of time. Thus, while the given averages are easy to compute, they do not tell us directly how long individuals might have to wait. Thus, in this problem, we will address questions of waiting times by developing a simulation.

    In particular, the program will read the average number of people needing service per hour and the average time a clerk requires to service a customer. The program then will keep track of individuals as they enter and leave the checkout line(s), and we record how many customers were served and how long they waited. More precisely, we divide time into short intervals, and we use the averages given to determine the probability that the person will enter the line(s) during a time interval. We also determine the probability that a person at the clerk will finish. Then we proceed one time interval at a time. By using a random number generator, we follow people as they enter and leave the queue(s). We record when they enter; and when they finish, we compute how long we waited.

    This discussion suggests the following outline (following an imperative problem-solving paradigm):

    1. Identify (read) program parameters

      1. Number of queues for this simulation.
      2. Average number of people arriving per hour.
      3. Average time for clerk to serve one customer.
    2. Initialization

      1. Initialize queue(s) and random function
      2. Set processing totals to 0 for time waited, maximum time waited, and number of people processed.
      3. Determine data for one time interval.
        1. Length of interval.
        2. Probability a person will enter line in the time interval.
        3. Probability a person in line will finish in the time interval.
    3. Repeat for each time interval.

      1. If a person has finished in that interval:
        1. Delete person from queue.
        2. Compute time in queue.
        3. Add time to total.
        4. Check time against maximum waiting time.
        5. Note another person has finished.
        6. If a customer is waiting in the relevant queue, that person moves from the queue to this clerk.
      2. If a person enters the system:
        1. If a clerk is free:
          1. person goes to the clerk
          2. waiting time is 0 for this person
        2. If no clerk is free:
          1. Determine which queue is shortest
          2. Record the person's time as a new entry on the shortest queue.
      3. Revise time for the start of the next interval.
    4. Print results.

      1. Print number of people served.
      2. Compute and print the average waiting time.
      3. Print maximum time waited.

    Timing Issues

    In order to track timing through the simulation, there is a need for a common [simulated] clock. Also, customers might be expected to keep track of their own time waiting in queues or at a clerk, while clerks might be expected to determine when they are finished with a customer.

    Work for this Problem

    Develop an object-oriented program to simulate waiting times for this multiple-queue problem. Your solution should include these elements:

    1. Identify the classes and objects needed for this simulation. Include a class diagram with any needed hierarchy of classes. Of course, any object-oriented design will need to respect "is-a" and "has-a" relationships.

      For example, statistics on waiting times and number of customers must be kept somewhere, and this is a candidate for another class.

    2. Utilize Java's ArrayDeque, a Double-Ended Queue, as the implementation for a queue. Multiple queues should be implemented as an array of ArrayDeque.

    3. Implement your design in Java.

    4. Write a test plan that provides reasonable confidence that the simulation is correct. (Since the program is a simulation based on random numbers, specific results may vary from one run to the next. However, various cases and trends can be compared against reasonable expectations.)

    5. Test your program, following the test plan, and write one or more paragraphs on the results of your testing.

    6. [Extra Credit] Run a series of simulations to compare the effectiveness of the two models — specifically determining the relative waiting times of customers in each model under varying conditions.

Supplemental Problem 4

  1. An interactive application is to provide information about a school's faculty. Overall, the following types of data retrieval are to be supported:

    A Faculty Class: As might be expected, information for a faculty member will be stored in a Faculty class. Most fields are suggested by the fields to be printed, although the committee information requires some discussion:

    public class Faculty 
    {
       private String firstname;
       private String lastname;
       private String department;
       private int firstyear;
       private String rank;
       private ArrayList<CommitteeNode> committees;
    }
    

    The ArrayList will contain entries for each committee on which this faculty member serves. (More details shortly.)

    Faculty in a binary search tree:Since the roster of faculty members is dynamic, the faculty will be stored in a binary search tree, ordered by last name (if two faculty members have the same last then, then ordering is by first name). Such a structure allows efficient lookup by faculty member and efficient printing of the entire faculty directory in alphabetical order by name.

    Committee names in a hash table: Efficient searching of the members of committee should NOT require searching the entire roster of faculty. Thus, committee membership will be maintained through a separate list structure that is superimposed on Faculty objects. Here are some details:

    In addition, since one required capability of this application is to find the names of other faculty members on the same committee as a given person, the linked list for a committee should be doubly linked. Links forward and backward allow easy reference to members of a committee, given one person — one just goes forward and backward through the list to find all other members.

    Assignment: Implement the above design in Java. Your program should allow the insertion of faculty members into a binary search tree, followed by the creation of doubly-linked committees lists where the first linked-list reference is obtained by using a hash table with the committee name as key. Your program should then allow lookup of faculty and committees and printing of all faculty, as identified in the above specification. (In the interests of time, your program need not handle deletion of a faculty member's record or changing committee assignments.)

    To get started, the following Java code shows the initial fields required for both Faculty and CommitteeNode classes.

    The following file(s) are available on MathLAN at directory /home/walker/207/java are available to help insert relevant data for the 2011-2012 academic year at Grinnell College.


This document is available on the World Wide Web as

http://www.cs.grinnell.edu/~walker/courses/207.sp12/suppl-prob.shtml

created 22 May 2008
last revised 5 May 2012
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.