CSC 207 Grinnell College Spring, 2013 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.

### 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).

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

• The first lines of any Java program should be comments containing your name, your mailbox number, this course number (207), an identification of assignment being solved, and an Academic Honesty certification. (You may not talk to anyone, except the instructor, a class mentor, or an evening lab tutor, for any Supplemental Problem.) For example:
```    /*****************************************************************
* Henry M. Walker                                               *
* PO Box Science II                                             *
* Program for CSC 207                                           *
*   Gambling Simulation                                         *
* Assignment for Monday, February 20                            *
*****************************************************************/

/* ***************************************************************
*   Written/online sources used:                                *
*     [include textbook(s),                                     *
*       CSC 207 labs or readings;                               *
*       complete citations for Web or other written sources]    *
*     [write "none" if no sources used]                         *
*   Help obtained                                               *
*     [indicate names of instructor, class mentors              *
*      or evening lab tutors, consulted                         *
*      according to class policy]                               *
*     [write "none" if none of these sources used]              *
*   My signature below confirms that the above list of sources  *
*   is complete AND that I have not talked to anyone else       *
*   [e.g., CSC 161 students] about the solution to this problem *
*                                                               *
*   Signature:                                                  *
*****************************************************************/

```
• Comments should identify the logical sections of the work and provide a high-level overview of the main steps being performed.
• Comments should clarify any complex logic or data structure — what is the motivating idea behind the block of complex code?
```  /***
* equals is a method
* @param first is a String
* @param last is a String
* @returns a boolean value
*/
equals (String first, String last)
```
• Any code should be reviewed for readability, including
• indenting to highlight logical structure
• descriptive variable names
• lines of code short enough to avoid line wrap when printed
• use of methods to divide complex processing into manageable parts

• each class
• each field
• each method (including each parameter and any return data

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

4. Commentary (typed or handwritten) regarding your testing of the code, including:

• A numbered listing of the circumstances that can reasonably arise in this problem.
• For example, if a program is to categorize data, the listing should include a statement of the categories; If some category could be obtained in several ways, the statement should identify each circumstance that could lead to the category.
• As another example, if the order of initial data might impact processing, then the listing should include circumstances to test the order of input data.
• A listing of test cases to be considered, with the expected outcome.
• For each numbered item in the listing of possible circumstances, a corresponding test case should be identified.
• Each test case should be specific, including what data will be considered and what output is expected.
• A listing of the actual test runs (copying and pasting into a separate document is allowed). Each test run should be annotated (writing on the printout is acceptable), identifying which test case is being run and whether or not the output produced is correct.
• Once testing is completed, prepare a separate statement that argues why your program is correct, based upon the evidence from your test runs.

Email lab each class, test plan, test runs, and statement of correctness as separate attachments to grader-207@cs.grinnell.edu. Please include the assignment title (e.g., Lab 2) and the name of all co-authors in the Subject line.

• Since every programming task should yield readable and carefully tested code, the grading of all programs for this course will begin with the following algorithm (expressed in C or Java format):
```
|| (missing pre- or post-conditions)
|| (formatting_does_not_show_structure)
|| (no_evidence_of_compilation)
|| (no_test_plan___no_listing_of_circumstances__OR__no_listing_of_test_cases)
|| (no_test_runs)
|| (no_commentary_on_correctness))
|| (no_signed_certification_regarding_sources_and_help)
```
• When a program is submitted according to the instructions specified above, it should be understood that the various pages reflect the same program. That is, the javadoc listings should have been generated by Eclipse from the code printed, and Eclipse should have run the code to generate the printed output. With this understanding, editing of a javadoc file or an output file is strictly forbidden and will result in automatic failure on the assignment. Such editing also may raise questions of academic dishonesty; and, by College policy, any evidence of academic dishonesty must be turned over to the Academic Standing Committee for action.

Summary: Don't even think about editing a javadoc file or an output listing.

Two grading forms will be used in the grading of each supplemental problem.

• A general form provides feedback on many elements common to most or all object-oriented programs.
(This form is under development and may evolve through this semester.)
• A problem-specific form that evaluates specifics for an individual problem.

### A Simple Class Hierarchy

1. This problem introduces some simplified elements related to a program to track shopping in a grocery store. Many details would be expanded greatly for a real application, but this problem might make a [small] start.

Items available in a grocery store might be categorized as produce (e.g., vegetables, fruit, cheese, meat, etc.), beverages (bottled water, milk, soft drinks, energy drinks, etc.), and packages (boxes of crackers, noodles, tea, etc.). A class hierarchy to model this categorization of items follows:

To clarify,

• All materials in a store fall within a general category of a class Item.

• Every Item has a protected name field of type String that indicates the name of the grocery item (e.g., can of soup, box of macaroni and cheese, bottle of Diet Pepsi, etc.).
• Every Item has a protected cost field of type double that indicates the purchase price of this grocery item.
• Every Item has a method getCost that returns the cost of the item.
• Every Item has a method costPerUnit that computes and returns the amount a user pays per unit. Since an Item knows nothing about its units, this computation for a plain Item is the same as cost — the cost for 1 Item unit. (The computation of costPerUnit may differ in subclasses.)
• Every Item has a method toString that returns a nicely-formatted string containing name and cost information.
• Class Produce is a subclass of Item of fresh, uncooked ingredients.

• Every Produce has a private field pounds of type double that gives the weight of the object in pounds.
• Every Produce has a private field category of type String that gives the type of material, such as a vegetable, fruit, cheese item, ice cream, etc.
• Within Produce, method costPerUnit will need to return the cost per pound of the object, and toString should report weight and category, in addition to the data stored as part of an item.
• A Beverage is an Item for drinking.

• Each Beverage container holds a specified amount of liquid, reported in the private int field fluidOunces.
• When sold, the customer must pay the regular price plus a deposit, recorded in a private double field containerDeposit
• Within Beverage, method costPerUnit will need to return the cost per fluid ounce of the object, and toString should report number of fluid ounces and the amount of the deposit, in addition to the data stored as part of an item. In addition, method getCost will need to include both the actual cost of the item, but also the container deposit.
• A Package is a subclass of Item that comes in a rectangular box.

• Each Package object has dimensions for length, width, and height that are stored as private double fields.
• Each Package holds an amount of materials, reported in the private int field ounces.
• Within Package, toString should report the size and weight of the object, in addition to the data stored as part of an item. (Note that a Package is considered a single unit, so the costPerUnit method of Item need not be modified for this subclass.)

For this problem, you should implement the following:

1. Class definitions for Item and its subclasses Produce, Beverage, and Package

2. A ShoppingCart class, modeled upon the SchoolDirectory class from the CSC 207 lab Generalization, Polymorphism, and Exceptions. The ShoppingCart class should have these features:

• A private array Cart of Item objects:
• The size of Cart is given by private field maxSize.
• Field currentSize gives the actual number of objects stored in Cart, in positions Cart[0] to Cart[currentSize-1].
• A method addItem places a new item object into the array, expanding the array as needed, and incrementing currentSize
• A method printCart should provide a listing of all items in the cart.
• A method totalCost should compute the total cost of all items in the cart.
• A method numberInCart should take a parameter String groceryName and return how many items in the current shopping cart have that name.
Notes:
• An easy way to compare strings is to use the built-in compareTo method. That is, if str1 and str2 are two strings, then str1.equals(str2) returns true if the two strings are the same (including case) and false if the two strings differ in any way.
• Although class Item and its subclasses contain a name field, this field is protected. Explain why numberInCarf cannot be implemented in ShoppingCart with the specified fields and method for Item and its subclasses.
• To implement numberInCart, class Item could be expanded in two ways (for reasons of correctness and security, we do not consider changing name to public.)
• A method getName() could be added to class Item to return the name string.
• A method equals (String str) could be defined in class Item which returns true if the name in the Item matches str and returns false otherwise.
Modify Item with one of these approaches in order to implement numberInCart. Include a comment explaining why you chose this approach for expanding Item.

### An Investing Simulation

1. Investing money for the future is a complex endeavor, with many philosophical, practical, and legal subtleties. This problem explores some simple approaches to investing — ignoring many details and legal complications. For example, different types of investing options may have different tax implications. Consider this problem as suggesting a type of computing application involving simulation rather than a tool for actual investing.

For simplicity, the following discussion assumes that an individual is investing, that bonds are issued by local, state, or federal governments, and that stocks are issued by companies. Although I think the following statements reflect the basic practices for different types of investing, you are warned that some details may be incorrect!

Background:

People can invest money in several types of financial instruments. Here are a few of the alternatives:

1. savings accounts
• an person places money in a bank account
• the bank pays interest (compounded at specified intervals) as a percentage of the amount currently in the account, and this amount is added to the current value of the account
• the individual may withdraw any amount up to the full account total at any time without penalty
• although invested money is owned by a bank, accounts are insured (up to a substantial amount) in case the bank fails.
2. bonds
• a governmental body issues (i.e., sells) a bond for a given face value for a specified interval (often 10, 20, 25, or 30 years) with a given interest rate.
• the purchaser of the bond pays face value
• at specified intervals (e.g., 4 times a year), the governmental body pays interest to the purchaser
• the governmental body pays back the full face value of the bond after the specified length of the bond, but the purchaser cannot receive this payment earlier
• the investment is backed by a wide range of local, state, and federal laws, so the underlying value of the bond does not decrease
3. US government savings bonds
• a purchaser creates an account with the US government
• the purchaser can buy a bond in any amount between \$25 and \$10,000 per calendar year at a specified interest rate for a period of time up to 30 years.
• the current annual interest rate for US government EE savings bonds is 0.20%.
• the government credits the purchaser's account with interest paid every month, based on the current value of the bond. The current value plus recent interest is considered to be a redemption value.
• every six months, the government includes interest paid into a new base amount or current value. That is, the same base amount is used to compute interest every month for a six month period. This interest goes toward the redemption value of the bond, but the current value (or the base for the interest computations) is updated only every six months. The jargon is that interest is computed monthly but compounded every six months.
• an individual may cash in the the savings bond at any time after one year. However, according to the US Treasury, "if you cash them in before 5 years, you lose the last 3 months' interest. (For example, if you cash in an EE Bond after 18 months, you get the first 15 months of interest.)" To clarify (perhaps) from the Savings Bond Advisor, "Savings Bond interest accrues (is added to the value of the bond for redemption calculations) monthly, but compounds (is added to the value of the bond for interest rate calculations) every six months."
• a US savings bond is backed "full faith and credit of the United States government", so the underlying value of the bond does not decrease
4. stocks
• a company issues stocks as a means to generate revenue for expansion or other functioning
• an investor (called a stockholder) purchases stocks and becomes a part owner of the company
• an investor receives periodic dividends (quarterly, semi-annually, or annually), based on the performance of the company. Typically, the amount paid is approximately a percentage of the amount invested (subject to various details)
• stocks are traded among investors (e.g., through stock exchanges), so the price of stocks can go up and down.
• investors may lose much or all of their money, if the company closes
• if a company's stock is considered risky, dividends may be relatively high as an incentive for investment
• if a company is consider well run and stable, dividends may be relatively low as there is little investor risk

Class Hierarchy

This discussion of investment alternatives motivates the following class hierarchy:

In this problem, you must use the fields and methods indicated in your implementation. (You may add additional private fields and private methods, if you wish, but each class must include the elements specified. All indicated fields should be private or protected; all indicated methods should be public.)

Expanding upon this diagram,

• Abstract class Investment is a base class with various (protected) fields that record various elements of any investment.
• The class should have relevant constructors.
• Users of this class should be able to obtain information about details of the investment (e.g,. the fields), but once an investment is made, the investment details should not change (i.e., one needs getters, but not setters).
• Every investment vehicle will need to compute interest or dividends on a monthly basis. If dividends are computed only each quarter or 6 months, a monthly update may not change any amounts until the proper number of months has passed. The update should return any interest or dividends paid to the user over the months specified (if any) as well as update the current or redemption value, if needed. Since update is different for the various types of investments, this method should be abstract in Investment.
• Class SavingsAccount should model interest payments in a bank. All interest obtained is used to increase the current value of the account, so the update method adds interest to the current value, but always returns 0 as the amount paid to the bond's owner. In the context of a savings account, the redemption value is the same as the current value.
• Class Bond should model general bonds, where a purchaser receives a designated amount of interest at specified intervals (measured in months). Once issued, the current value of the bond never changes. The bond may not be cashed in until the term of the bond is reached, so the redemption value is zero for any time prior to the term of the bond. Thereafter, the redemption value is the same as the current value of the bond.
• Class USSavingsBond is like a Bond, except
• the redemptive value is increased each month, but
• the current value increases over a longer period (e.g., every six months)
• the Savings Bond is always cashed in for the redemption value
• the current value (the base for interest calculations) is only updated every several months (e.g., every six months)
• for the first several years of the Savings Bond (e.g., before five years), the redemption value does not reflect the interest of the past few months (e.g., 3 months).
• after a specified time (e.g., five years), monthly interest is added to the redemption value each month
• Class Stock computes a dividend periodically on its current value (which is the same as its redemption value). However, the current value may go up or down each year with a certain probability, and the amount of the loss or gain may vary according to the company.

Each class may have additional private fields as needed to aid in needed computations.

Assignment:

• Write code for the Investment, SavingsAccount, Bond, USSavingsBond and Stock classes.
• Write a Portfolio class that creates an initial amount of investments for \$25,000 and follows the return on that investment over 20+ years.
• Some current statistics may help identify reasonable data.
• Current savings account rates seem to be in the range 0.85% to 3.00% (rates generally are 0.85% to 1.00%, but the 3.00% rate is possible with one type of checking at the local University of Iowa Credit Union.)
• Current rates for municipal bonds seem to be in the range 1.85% to 3.60% (although higher rates are possible on potentially-risky investments).
• Stock dividends are highly variable, depending upon the perceived risk of the company and current market conditions. Recent reported ranges seem to range from 0.85% to 20%. Of course, higher rates may correspond to a higher risk of losing money on a stock's price.
• According to http://smallbiztrends.com,, "The 1995 BLS EST, 2000 BLS EST, and 2005 BLS EST lines each track the five year survival rates of the cohorts of new establishments founded in 1995, 2000 and 2005 respectively. Five years after they were started, 50, 49 and 47 percent of the new establishments started in 1995, 2000 and 2005, respectively, were still alive." (Here "BLS" refers to the US Bureau of Labor Statistics and EST refers to "establishments".) Overall, failure rates for new companies may be about 50% for the first five years of operation.
• Consider a portfolio including a mix of investment types over periods of 20 years. Run several cases, including the following
• Most or all of a portfolio is invested in one type of investment
• A portfolio contains equal amounts of each type of investment
• Do some basic strategies seem better than others (be sure to define what is meant by "better" in each case)?
• Select your portfolio examples as a means to test your code. That is, identify what evidence you would need to conclude that each class is working correctly, and construct one or more portfolios to test each situation.

Note: Although the theme of this problem is investing, the main purpose is to consider abstract classes, classes, inheritance, and testing. Modest points can be earned for an extensive portfolio analysis, but most points will relate to the class design, implementation, and testing. Actual investors are referred to economists for additional considerations regarding investment strategies.

### Queues of Different Priorities for Printing

1. When a printer serves multiple users, users may sent several print requests to the operating system, but only one file can be printed at a time. Thus, the operating system can direct a file from one print request to the printer, but the other requests must be stored in some type of data structure. The simplest approach involves a single queue. Each user sends one or more files to the operating system, and the operating system places the print requests on a queue. The operating system then sends the files to the printer one-at-a-time from the print queue. Of course, once a printer starts to print a file, the printer must complete that job before moving onto the next print request. Although this approach is simple and treats all jobs equally, this approach has the disadvantage that many short printing jobs (of only a few pages) may have to wait substantial amounts of time for a large print job (hundreds of pages) to finish.

One way to give some preference to certain print jobs is to create multiple queues of varying priorities. For convenience of notation, suppose a system has n queues, labeled q0, q1, q2, ..., qn-1. Suppose qi has priority i, where priority 0 is top priority, priority 1 is the next highest priority, ..., and priority n-1 is the lowest priority. That is requests in q0 are chosen before print requests in any other queue, and requests in qn-1 must wait until requests from all other queues have been printed.

The division of print requests into queues of varying priorities can work well in many cases, but this approach has the drawback that low priority print requests may never be printed if a steady stream of higher priority requests enter the system. In operating-systems jargon, this situation is called starvation; some work is never done because the system spends all of its time on other processing.

To avoid the possibility of starvation, a typical approach is to periodically move a print request from a low-priority queue to the next higher priority queue, as this would cause any print request to eventually move up to the head of the highest priority queue. To specify this promotion from one queue to the next more precisely, suppose that every time k requests from queue qi have been sent to the printer, the system removes a request from queue qi+1 and enqueues the request on queue qi.

The Printing Protocol

The following diagram provides an overview of the process of user submission of print requests, their placement on an appropriate queue, and their subsequent transmission to the printer for printing:

The formal protocol follows:

• At any time, a user may send a print request to the operating system.

• The request specifies the name of the file and the number of pages to be printed.
• The operating system uses an enqueue operation to place the print request on a queue, based on the number of pages to be printed

• Three algorithms for determining the relevant queue are given later in this problem.
• If the printer is idle, the operating system will select a print request from the highest priority non-empty queue.

• If the printer is busy, the operating system simply collects print requests in its queues.

• If the printer completes a print request, the operating system processes print requests as follows:

• If no print requests remain unprocessed, the system waits until a new request is submitted.
• If one or more print requests are unprocessed, the operating system uses a dequeue operation on the non-empty queue of highest priority.
• Whenever a dequeue operation is executed k times for any queue qi, the operating system finds the highest priority, non-empty queue qj with j > i. The operating system then uses the dequeue operation on qj to retrieve a print request, and that request is then immediately enqueued onto qi

Determining Initial Print-request Priority

The print-queue protocol above requires the operating system to determine which queue should be used for each new print request submitted by the user. Three assignment approaches follow:

1. All print requests are put on queue q0; that is, only one queue is used, and requests are printed in strict FIFO order.
2. n queues are used, and print requests are assigned initially to queues based on their size.
• Files of size 1-10 pages go initially to queue q0,
• Files of size 11-20 pages go initially to queue q1,
• Files of size 21-30 pages go initially to queue q2,
• ...
• Files of size i pages go initially to queue qi/10 (for i < 10 (n-1)),
• ...
• All files of 10(n-1) or more pages go to queue qn-1,
3. n queues are used, and a print request for a file of size i is initially assigned to queue qi%n.

Problem to be Solved

Supplemental Problem 3 is to investigate the extent to which multiple queues and different assignment algorithms have an impact on the average waiting time for users' print requests.

For the purposes of this problem, suppose that printing one page requires one unit of time. The simulation described below will cover 1000 units of time, and the simulation will need a "clock" variable that keeps time units 0, 1, 2, ..., 999.

1. Identify a Queue class for use with this problem. (If possible, use a queue class from the Java Library, although you may need to expand it to know how many times a dequeue operation has been called since the queue was last empty.)
2. Define a PrintRequest class that contains relevant information regarding a user request for printing. Likely, this PrintRequest class will need fields to record the number of pages to be printed and the clock time when the user submitted a print request.
3. Define a Printer class with [at least] these methods (beyond a constructor)
• a boolean printerIdle() method that returns true if the printer currently is not processing a print request, and false if the printer is busy processing a Print Request (i.e., the printer is printing a requested file).
• a boolean printFile (PrintRequest pr) method:
• if the printer is idle, the printer will start processing the given print request, and the method returns true
• if the printer is already processing another Print Request, the new Print Request pr is ignored, and the method returns false
• a PrintRequest processForOneUnit() method that prints one page of the current print request
• if the printer is idle, or if the current Print Request is NOT completed within 1 unit of time, then processForOneUnit returns null. (Internally, the printer object should record that one additional page of the current Print Request has been printed.)
• if the current Print Request is completed in the current time unit, the method returns the current PrintRequest object that just finishes printing.
4. Write a Simulation class for the following simulation:
• The program will read four parameters from the terminal:
• The probability that some user will make a print request in a single time interval
• The number n of queues to be used
• The number k of dequeue operations from one queue before an item from a lower-priority queue is promoted
• The algorithm ("A", "B", or "C" from above) for determining how the operating system will decide which queue will be used for a user's print request.
• Processing proceeds one time unit at a time, based upon a "clock" variable.
Processing in one time unit involves the following:
• If the printer is in use, then 1 page of the current job is printed (so the print job is 1 page closer to completion).
• A user may or may not make a print request. For this simulation, the likelihood that a print request is generated in one time of time should be based on a random number generator and a user-entered probability. If a print request is generated, processing in the simulation should depend upon these parameters.
• The number of pages for the print request should be determined randomly between 1 and 100 pages.
• A new Print Request object is created, containing the number of pages for the job and the starting "clock" time that this request entered the queue.
• The user's request is submitted to the operating system in the form of an object with the clock time and print size.
• The operating system places the new Print Request object on the appropriate queue.
• If the printer is idle, and if at least one print request is pending, then
• a print request is selected from the multiple queues, as described above.
• the wait time (number of time intervals of waiting) for this Print Request is used to update both a maximum wait time and a total average wait.
• the print request is sent to the printer object.
• After the "clock" reaches 1000 time units, no new Print Requests should be generated, but the simulation should continue until all existing Print Requests have been processed.
5. At the end of the simulation, the program prints:
• the maximum waiting time for any Print Request
• the average waiting time for all processed Print Requests

To investigate the impact of different queue-selection strategies, testing should include each of the queue-selection approaches and several loads (numbers of Print Requests entering over the simulation).

This document is available on the World Wide Web as

```http://www.walker.cs.grinnell.edu/courses/207.sp13/suppl-prob.shtml
```