Part A.
Part B. 5 5
Problem 2
Part A.
input data: 1 2 3<eof>
return value of isIncrOrder(vals): true
Part B.
input data: 2 1 1 3<eof>
return value: false
Part C. New code shown in bold.
public static boolean hasAdjacentPair(Scanner in) {
int last; // needs to be defined outside of the blocks
boolean foundPair = false;
if (in.hasNextInt()) { last = in.nextInt(); }
while (in.hasNextInt()) {
int val1 = in.nextInt();
int val2 = in.nextInt();
if (val1 == val2 last) { foundPair = true; }
last = val1;
}
return foundPair;
}
Problem 4
There are several different correct solutions. Here are two of them.
mkdir 09-06 cd 09-06 cp $ASNLIB/public/09-06/* .alt solution:
mkdir 09-06 cp $ASNLIB/public/09-06/* 09-06
Problem 5
Solution shown in bold. There are a few variations on this solution. A solution that stored all the temperatures (and involved one or more loops) could get most of the points.
public class TempStats {
public static final int MIN = -100;
public static final int MAX = 150;
public static final int NO_TEMPS = MIN - 1;
private int high;
private int low;
private int total;
private int sum;
private int [] counts;
public TempStats() {
high = MIN - 1;
low = MAX + 1;
total = 0;
sum = 0;
counts = new int[MAX - MIN + 1];
}
public void add(int temp) {
if (temp > high) { high = temp; }
if (temp < low) { low = temp; }
total ++;
sum += temp;
counts[temp - MIN]++;
}
public double getAverage() {
if (total == 0) { return NO_TEMPS; }
return sum / (double) total;
}
public int getLow() {
if (total == 0) { return NO_TEMPS; }
return low;
}
public int getHigh() {
if (total == 0) { return NO_TEMPS; }
return high;
}
public int getNumOccur(int temp) {
assert (MIN <= temp && temp <= MAX);
return counts[temp-MIN];
}
}
Problem 6
public static int removeNegatives(int[] nums, int size) {
int dest = 0;
for (int source = 0; source < size; source++) {
if (nums[source] >= 0) {
nums[dest] = nums[source];
dest++;
}
}
return dest;
// dest is the number of values we moved (i.e., number of non-negative values)
}