[Skip to Body]
Primary:
[Front Door]
[Current]
[Glance]
-
[Honesty]
[Links]
[Syllabus]
Groupings:
[EBoards]
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Readings]
[Reference]
Misc:
[SamR]
[Java 1.4.2 API]
[EIJ]
[CS152 2000F]
[CS153 2004S]
Distributed: Friday, 29 October 2004
Due: 11:00 a.m., Friday, 5 November 2004
No extensions.
This page may be found online at
http://www.cs.grinnell.edu/~rebelsky/Courses/CS152/2004F/Exams/exam.02.html.
Contents
BinarySearcher.java
TestBinarySearch.java
BigIntegerComparator.java
NewArrayBasedQueue.java
TestNABQ.java
CoinCounter.java
TestCoinCounter.java
There are four problems on the exam. Some problems have subproblems. Each problem is worth twenty-five points. The point value associated with a problem does not necessarily correspond to the complexity of the problem or the time required to solve the problem.
This examination is open book, open notes, open mind, open computer, open Web. However, it is closed person. That means you should not talk to other people about the exam. Other than that limitation, you should feel free to use all reasonable resources available to you. As always, you are expected to turn in your own work. If you find ideas in a book or on the Web, be sure to cite them appropriately.
Although you may use the Web for this exam, you may not post your answers
to this examination on the Web (at least not until after I return exams
to you). And, in case it's not clear, you may not ask others (in person,
via email, via IM, by posting a please help
message, or in any
other way) to put answers on the Web.
This is a take-home examination. You may use any time or times you deem appropriate to complete the exam, provided you return it to me by the due date.
This exam is likely to take you about four to six hours, depending on
how well you've learned topics and how fast you work. You should not
work more than eight hours on this exam. Stop at eight hours and
write There's more to life than CS
and you will earn at
least 80 points on this exam. I would appreciate it if
you would write down the amount of time each problem takes, and will
award you two points of extra credit for doing so. I expect that
someone who has mastered the material and works at a moderate rate should
have little trouble completing the exam in a reasonable amount of time.
Since I worry about the amount of time my exams take, I will give two
points of extra credit to the first two people who honestly report that
they've spent at least five hours on the exam or completed the exam.
(At that point, I may then change the exam.)
You must include both of the following statements on the cover sheet of the
examination. Please sign and date each statement. Note that the
statements must be true; if you are unable to sign either statement,
please talk to me at your earliest convenience. You need not reveal
the particulars of the dishonesty, simply that it happened. Note also that
inappropriate assistance
is assistance from (or to) anyone
other than Professor Rebelsky (that's me).
1. I have neither received nor given inappropriate assistance on this examination.
2. I am not aware of any other students who have given or received inappropriate assistance on this examination.
Because different students may be taking the exam at different times,
you are not permitted to discuss the exam with anyone until after I
have returned it. If you must say something about the exam, you are
allowed to say This is among the hardest exams I have ever
taken. If you don't start it early, you will have no chance of
finishing the exam.
You may also summarize these policies.
You may not tell other students which problems you've finished.
You may not tell other students how long you've spent on the exam.
You must both answer all of your questions electronically and turn in a printed version of your exam. That is, you must write all of your answers on the computer, print them out, number the pages, put your name on every page, and hand me the printed copy. You must also email me a copy of your exam by copying your exam and pasting it into an email message. Put your answers in the same order as the problems. Please write your name at the top of each sheet of the printed copy. Doing so will earn you two points of extra credit.
In many problems, I ask you to write code. Unless I specify otherwise in a problem, you should write working code and include examples that show that you've tested the code. Unless I specify otherwise, you should document your code (using javadoc-style comments for classes, fields, and methods and slash-slash comments for particular algorithm details).
Just as you should be careful and precise when you write code and documentation, so should you be careful and precise when you write prose. Please check your spelling and grammar. Since I should be equally careful, the whole class will receive one point of extra credit for each error in spelling or grammar you identify on this exam. I will limit that form of extra credit.
I will give partial credit for partially correct answers. You ensure the best possible grade for yourself by emphasizing your answer and including a clear set of work that you used to derive the answer.
I may not be available at the time you take the exam. If you feel that a question is badly worded or impossible to answer, note the problem you have observed and attempt to reword the question in such a way that it is answerable. If it's a reasonable hour (before 10 p.m. and after 8 a.m.), feel free to try to call me in the office (269-4410) or at home (236-7445).
I will also reserve time at the start of classes next week to discuss any general questions you have on the exam.
Topics: Documentation, testing, reading code, asymptotic analysis.
You should recall the binary search method from CSC151. Binary search allows us to quickly find an element in a sorted array by checking the middle element of the portion of interest and discarding half depending on that value. Here is a class, BinarySearcher, which implements that method.
package rebelsky.exam2;
import java.util.Comparator;
/**
* Something that knows how to do binary search on arrays using a
* specified comparator.
*
* @author Samuel A. Rebelsky
* @author YOUR NAME HERE
*/
public class BinarySearcher
{
// +--------+--------------------------------------------------
// | Fields |
// +--------+
/**
* The comparator used to determine the order of
* elements in an array.
*/
Comparator metric;
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
/**
* Build a new searcher that uses a particular
* comparator.
*/
public BinarySearcher(Comparator _metric)
{
this.metric = _metric;
} // BinarySearcher(Comparator)
// +----------------+------------------------------------------
// | Public Methods |
// +----------------+
/**
* WRITE ME!
*/
public int binarySearch(Object findMe, Object[] stuff)
throws Exception
{
int lb = 0; // The lower-bound of the portion of interest
int ub = stuff.length - 1; // The upper-bound
while (lb <= ub) {
int mid = (lb + ub)/2;
int c = metric.compare(findMe, stuff[mid]);
if (c == 0) // Found it!
return mid;
else if (c < 0) // Middle element too big!
ub = mid-1;
else // Middle element too small!
lb = mid+1;
} // while
// Whoops, doesn't seem to be there
throw new Exception("Not found!");
} // binarySearch(Object)
} // class BinarySearcher
a. Write the documentation for binarySearch. Make sure
that you indicate preconditions and postconditions.
b. Binary search only works on properly ordered arrays. Hence, it might
be useful to have a method, boolean isInIncreasingOrder(Object[]
stuff), that determines whether stuff is in increasing
order according to the metric. Write that method.
c. Although I very much like students to test preconditions, it would
make me very upset to see you call isInIncreasingOrder as
part of binarySearch. Why?
Topics: Queues, arrays
As you may recall, we can implement a queue using an array and two indices,
first, which keeps track of the position of the front of
the queue, and last, which keeps track of the position of
the back of the queue. We add elements at last (after
incrementing it) and remove elements at first (before
incrementing it).
Because this implementation clears space at the beginning of the array
and fills space at the end, we will find that there are times when there
are only a few elements in the array, but last reaches the
end of the array. Our first strategy was to shift everything left in
the array. However, we realized that the first strategy can lead to
some inefficiencies.
To eliminate these efficiencies, Mr. Conor suggested that we wrap
around
to the beginning of the array, rather than shifting left.
Here is the start of such an implementation:
package rebelsky.exam2;
import rebelsky.linear.Queue;
/**
* An implementation of queues using arrays. Currently incomplete.
*
* @author Samuel A. Rebelsky
* @author Kevin Conor
* @author YOUR NAME HERE
* @version 1.01 of October 2004.
*/
public class NewArrayBasedQueue
implements Queue
{
// +--------+--------------------------------------------------
// | Fields |
// +--------+
/** The index of the "last" thing. */
int last;
/** The index of the "first" thing. */
int first;
/** The stuff actually in the queue. */
Object[] contents;
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
public NewArrayBasedQueue()
{
this.last = -1;
this.first = 0;
this.contents = new Object[3];
} // NewArrayBasedQueue()
// +---------+-------------------------------------------------
// | Methods |
// +---------+
public void put(Object addMe)
{
this.last = this.last + 1;
// Have we run off the end? If so, wrap around to
// the beginning.
if (this.last == this.contents.length)
this.last = 0;
this.contents[this.last] = addMe;
} // put(Object)
public Object get()
throws Exception
{
// Note that the following line throws an exception
// if the queue is empty. Hence, the remaining lines
// will not be executed.
Object returnMe = this.peek();
this.contents[this.first] = null; // Actually remove it.
++this.first;
if (this.first == this.contents.length)
this.first = 0;
return returnMe;
} // get()
public Object peek()
throws Exception
{
if (this.contents[this.first] == null)
throw new Exception("It's empty!");
return this.contents[this.first];
} // peek()
public boolean isEmpty()
{
return this.contents[this.first] == null;
} // isEmpty()
} // class NewArrayBasedQueue
This implementation has at least one significant flaw: It doesn't expand the array when the queue fills. Fix that flaw. You may find TestNABQ.java useful for your testing.
Topics: Algorithm design, efficiency
A famous computer science problem is the coin minimization problem. Given a set of coin values (e.g., 1, 5, 10, 25, 50 or 2, 3, 8, 25, 40), and a particular price, find the fewest coins that make that particular value. For example, given coin values of 2, 3, 8, 25, 40, the fewest coins to make a value of 19 is 3 (8, 8, and 3) and the fewest coins to make a value of 50 is 2 (25 and 25).
How do you figure out the fewest coins? That's what this problem is about.
One possible solution is the greedy solution: To find the fewest coins, assume you use as many as possible of the most expensive coin, and then as many as possible of the next most expensive coin, and so on and so forth.
a. Give an example that shows that the greedy solution doesn't always produce the correct answer.
A more correct solution is the exhaustive search
solution. For each
denomination, we assume that we use one of that denomination, reduce
the amount appropriately, and recurse. We then take the smallest of
those solutions. Here is an implementation of that solution:
package rebelsky.exam2;
/**
* Something that helps us count coints.
*
* @author Samuel A. Rebelsky
* @author YOUR NAME HERE
*/
public class CoinCounter
{
// +--------+--------------------------------------------------
// | Fields |
// +--------+
/**
* The valid coin values.
*/
int[] denominations;
// +--------------+--------------------------------------------
// | Constructors |
// +--------------+
/**
* Build a new coin counter for a particular set of denominations.
*
* @pre
* The values in _denominations must be stored in
* decreasing order.
* @pre
* All values in _denominations must be positive.
*/
public CoinCounter(int[] _denominations)
{
this.denominations = _denominations;
} // CoinCounter(int[])
// +----------------+------------------------------------------
// | Public Methods |
// +----------------+
/**
* Determine the fewest number of coins necessary to
* make a particular price.
*
* @exception Exception
* If it is not possible to make that price.
*/
public int fewestCoins(int price)
throws Exception
{
// Simple solution: No coins needed for no price.
if (price == 0)
return 0;
// Fewest represents the fewest coins we've done so far
int fewest = Integer.MAX_VALUE;
for (int i = 0; i < this.denominations.length; i++) {
int coin = this.denominations[i];
if (coin <= price) {
try {
int sub = this.fewestCoins(price-coin);
if (sub+1 < fewest)
fewest = sub+1;
} // try
catch (Exception e) {
// It's okay we failed, we'll just
// try a different denomination.
} // catch
} // if (coin <= price)
} // for
// Make sure that we found a solution
if (fewest == Integer.MAX_VALUE)
throw new Exception("Can't make change for " + price);
return fewest;
} // fewestCoins(int)
} // class CoinCounter
You may find it useful to test the program with
TestCoinCounter.java.
b. Extend CoinCounter so that it lets you count the number
of recursive calls that the fewestCoins does. Make a chart
to show the growth in the number of recursive calls as the price increases.
Topics: Algorithm design, efficiency, arrays
As you may have noted, that implementation is not very efficient. As you may recall, we made another inefficient method (fibonacci) more efficient by storing intermediate values in a table (an array).
a. Rewrite fewestCoins to use a similar improvement.
b. Make a chart to show the growth in the number of recursive calls as the price increases. What does the new growth curve look like?
These are some of the questions students have asked about the exam and my answers to those questions.
CoinCounter, can we assume anything about the order of the denominations in the array? It seems to me that its values would have to be ordered from largest to smallest, but I don't see that as a precondition.(lb <= ub). Fixed.Fib.java and TestFib.java.BigIntegerComparator.java.BigIntegers to the binarySearch method when it expects an array of Objects. Could you explain?Object class is the implicit top levelsuperclass of every class, even if you don't write
extends Object. Hence, you can use any kind of object as a parameter to something that expects an Object. Java is smart enough to figure out that this also means that an array of a particular kind of object can be used whenever an array of Objects is expected.can't make exact change for that amountin problem 4?
Here you will find errors of spelling, grammar, and design that students have noted. Remember, each error found corresponds to a point of extra credit for everyone. I limit such extra credit to five points (seven because of the special problem mentioned below).
first and front [LA, 1 point]
Thursday, 28 October 2004 [Samuel A. Rebelsky]
Monday, 1 November 2004 [Samuel A. Rebelsky]
Wednesday, 3 November 2004 [Samuel A. Rebelsky]
Thursday, 4 November 2004 [Samuel A. Rebelsky]
[Skip to Body]
Primary:
[Front Door]
[Current]
[Glance]
-
[Honesty]
[Links]
[Syllabus]
Groupings:
[EBoards]
[Examples]
[Exams]
[Handouts]
[Homework]
[Labs]
[Outlines]
[Readings]
[Reference]
Misc:
[SamR]
[Java 1.4.2 API]
[EIJ]
[CS152 2000F]
[CS153 2004S]
Disclaimer:
I usually create these pages on the fly
, which means that I rarely
proofread them and they may contain bad grammar and incorrect details.
It also means that I tend to update them regularly (see the history for
more details). Feel free to contact me with any suggestions for changes.
This document was generated by
Siteweaver on Wed Dec 8 10:36:31 2004.
The source to the document was last modified on Thu Nov 4 15:21:19 2004.
This document may be found at http://www.cs.grinnell.edu/~rebelsky/Courses/CS152/2004F/Exams/exam.02.html.
You may wish to
validate this document's HTML
;
;
Check with Bobby