15-121 SPRING 2010 [CORTINA]

HOMEWORK 6 - due Tuesday, March 16

ELECTRONIC HANDIN AVAILABLE THURSDAY BY 5PM

PROBLEMS (10 pts)

  1. (1.5 pts) A group of n knights are standing around a round table as shown below.

    The knights are numbered from 1 to n in order around the table. The knights agree that they will leave the table using the following algorithm. The knights pick a number p between 1 and n, inclusive. Then starting with knight #1, p knights are skipped and the next knight leaves the table. For example, if there are 12 knights as in the picture and p = 6, then knights 1,2,3,4,5,6 are skipped and knight #7 leaves. After the knight leaves, the knights repeat the previous step again starting with the next knight. Continuing the example, knights 8,9,10,11,12,1 are skipped and knight #2 leaves next. This repeats until all of the knights have left the table. For this example, with n = 12 and p = 6, then the knights leave in the following order: [7, 2, 10, 6, 4, 3, 5, 9, 1, 8, 11, 12].

    You can model this problem using a queue. First put the numbers from 1 to n into the queue in order. Then remove and insert p times to skip p knights. Then remove once from the queue (but don't re-insert) to find out which knight leaves next. Repeat this process until the queue is empty.

    1. Compute the order that the knights leave the table if there are 10 knights around the table and p = 5. Show the contents of the queue after each knight leaves the table. (You should have 10 pictures of queues.)

    2. Write a method that has two parameters, n and p, that returns an ArrayList of integers that gives the order that the knights leave the table for the given values of n and p. You may assume that n > 0 and 1 ≤ p ≤ n. Your method must use a FIFOQueue to compute the solution.

  2. (1 pt) Complete the method below that reverses the order of the elements in a queue of strings using a LIFOStack:

    public static void reverse(FIFOQueue<String> q) {
    
    }
    

  3. (1.5 pts) Consider the ArrayQueue<E> class that implements a FIFOQueue<E> using an array (with wraparound). Suppose we wish to implement a priority queue, where the enqueue operation works as usual, but the dequeue removes and returns the maximum (highest priority) element in the queue.

    1. Rewrite the dequeue operation so that it removes and returns the largest element of the queue. You may assume that type E implements Comparable.

    2. What is the runtime complexity of your new dequeue method if there are n elements in the queue? Explain your answer.

  4. (1.5 pts) The following question deals with iterators used on array lists.

    1. Write a method that has one parameter, an ArrayList<String>. This method should use an enhanced for-loop (implicit iterator) to print out all of the strings in this array list that are longer than 10 characters. You may assume that all string references in the array list are non-null.

    2. Repeat part (a) using an explicit iterator (instead of using the enhanced for-loop).

    3. Write a method that has one parameter, an ArrayList<String>. This method should use an iterator to remove all of the strings in this array list that contain the character '!'.

  5. (1.5 pts) Consider the following Worker class:

    public class Worker {
    
    	private String name;
    	private double rate;  			// hourly wage (e.g. 12.25)
    	private static final double minimumHourlyWage = 7.25;
    
    	/**
    	 * Creates a new worker given the name and initial pay rate.
    	 * If the initial rate is less than the current minimum hourly wage,
    	 * the rate for this worker is set to the minimum hourly wage.
    	 * @param workerName The name for this worker.
    	 * @param initRate The initial hourly pay rate for this worker.
    	 */
    	public Worker(String workerName, double initRate) {
    		name = workerName;
    		if (initRate < minimumHourlyWage)
    			rate = minimumHourlyWage;
    		else
    			rate = initRate;
    	}
    
    	/**
    	 * Returns the current weekly salary for this worker. The
    	 * salary is computed as a flat salary assuimng 40 hours of
    	 * work regardless of hours actually worked.
    	 * @return The current weekly salary for this worker.
    	 */
    	public double getSalary() {
    		return rate * 40.0;
    	}
    
    	/**
    	 * Returns the name of this worker.
    	 * @return The name for this worker.
    	 */
    	public String getName() {
    		return name;
    	}
    
    	/**
    	 * Sets the hourly pay rate for this worker to the new rate given.
    	 * If the new rate is less than the current minimum hourly wage,
    	 * the rate for this worker is set to the minimum hourly wage.
    	 * @param newRate The new rate for this worker.
    	 */
    	public void setRate(double newRate) {
    		if (newRate < minimumHourlyWage)
    			rate = minimumHourlyWage;
    		else
    			rate = newRate;
    	}
    }
    

    1. Add equals and toString methods to the Worker class so that they override the methods inherited from Object. Two workers are considered equal if their pay rates are the same.

    2. Create a subclass of Worker named HourlyWorker that has an additional int field named hoursWorked. An hourly worker is paid at the worker's pay rate for up to the first 40 hours and 1.5 times the pay rate for any additional hours worked beyond 40 hours. Two workers are considered equal if they have the same rate AND they work the same number of hours. This class should provide the ability to set the hourly rate to a new value and to set the hours worked to a new value.

      The constructor for your subclass should contain three parameters to set the name, rate and hours worked. (If the hours worked is less than 0, set the hours worked to 0.) Override any methods that need to be overridden and add any new methods that are absolutely necessary. Do not add any additional fields or methods that are not necessary. Do not change any part of the original Worker class except for code you need for part (a).

  6. (1 pt) Moe (the bartender) wants to create a subclass of ArrayList called MoeArrayList that is an arraylist that has an add operation that not only adds an element to the end of the list, but it also removes the first element. He decides to override the add method as shown below:

    public boolean add(E element) {
        add(element);   	// add to parent array list
        remove(0);		// remove last element from parent array list
        return true; 	
    } 
    

    Explain why this implementation is incorrect. What happens if he tries to run this method?

  7. (1 pt) The following code fragment illustrates the principle of polymorphism. Explain.

    LIFOStack<Integer> s;
    s = new ArrayStack<Integer>();
    s.push(1);
    s.push(2);
    s.push(3);
    s = new ListStack<Integer>();
    s.push(4);
    s.push(5);
    s.push(6);
    

  8. (1 pt) What are the similarities and differences between Java interfaces and abstract classes?

PROGRAMMING PROJECT (10 points)

A molecule is made of two or more atoms, where each atom can occur more than once. An atom is represented by an atomic symbol consisting of a single uppercase letter or an uppercase letter followed by a lowercase letter (e.g. H, O, Fl, Na). An atom also has an atomic number that represents the number of protons in that atom. For example, the chlorine atom (Cl) has an atomic number of 17, which means it has 17 protons. A molecular formula is a non-empty sequence of atomic symbols (e.g. KBr, CO, LiCl). Part of the formula may be repeated by enclosing it in parentheses followed by an integer between 2 and 99 (e.g. Ca(OH)2). The parentheses are omitted if the repeating component is a single atom (e.g. H2O, C6H12O6, Na2SO4, Ni(NO3)2). A molecular formula can consist of a single atom (e.g. H) or a single atom repeated (e.g. O3), and it can consist of multiple levels of parentheses (e.g. Co3(Fe(CN)6)2).

Assignment

Write a Java program that has a method that takes a string representing a valid molecular formula and computes and returns the total number of protons in the molecule. Your method should use a stack to keep track of partial results as you encounter subexpression in the chemical formula. You may assume that the atoms in the formula all have atomic numbers no greater than 54 and appear in the truncated periodic table shown below. Each box shows the atomic symbol along with its atomic number.

  1. Use the Java class Stack for your stack class. Do not call any methods except push, pop, empty, and peek.

  2. The formula can potentially have any number of layers of parentheses.

  3. You may assume that if an integer is given in the formula it will be in a valid location and its value will be between 2 and 99, inclusive.

  4. You may assume that the given formula is valid, including only atoms shown above and proper layering of parentheses.

Your class should also have a main method that tests your formula computation method. See the Testing section for the format for the input and output for testing.

Testing

You should write your main method so that it reads input from the keyboard (standard input) and outputs its results to the console (standard output) for testing. The first line of input should be the number of test cases to be executed. Subsequent input will be one chemical formula per line. For each formula, output the number of protons in the formula. Each output should be on a separate line. You do not need any additional prompts or output text.

Example input:

7
H
KBr
Ca(OH)2
H2O
C6H12O6
Ni(NO3)2
Co3(Fe(CN)6)2

Example output:

1
54
38
10
96
90
289

To speed up your testing, you can put your input data into a text file and use redirection. See TESTING USING THE COMMAND LINE from Homework 5 for more information.

Additional Requirements

  1. Add comments in your methods to explain your code where necessary. Use appropriate variable names for self-documentation and indent properly.

  2. Include a plain text file testdata.txt that has the test cases above and additional test cases to demonstrate that your program works correctly for as many different cases as you can.

Hand-In Instructions & Late Submissions

Your submitted zip file should include the complete Java program and your sample input test data file testdata.txt.

See the course website for instructions on how to hand in your program and the policy for late submissions.