Your method swapPairs should swap two consecutive elements repeatedly, not just the first two. In the sample solution, the head of the while loop should read
while (i < letters.length - 1) {
instead of while (i < letters.length - 2).
There's a small flaw in the example: Your function should return 3 because 1, 4, and 7 appear in both arrays.
The expression (int) Math.random() * N returns a random element of { 0, 1, 2, ..., N-1 }. It never returns N. In the sample solution, the while loop for initializing faceShown is missing a statement. The loop should read
while (i < 6) {
faceShown[i] = false;
i = i + 1;
}
The sample solution will not print the length of the longest, but the length of the last nondecreasing sequence. The correct solution should look like
public static void main(String[] args) {
int lastNum = -1; // number previously entered
int length = 0; // length of current nondecr. subsequence
int maxLength = 0; // length of longest
nondecr. subsequence so far
int num; // current number
while (lastNum != 0) {
num = in.ReadInt();
if (num != 0) {
if (num >= lastNum)
// if new elem is at least as big as old one
length
= length + 1; // count it
else
length
= 1; // one element is always nondecreasing
if (length > maxLength)
maxLength = length; // update info on
longest sequence
lastNum = num;
// save number for next round
}
}
System.out.println("Length of longest nondecr. subseq. is " +
length);
}
Two lines are missing in the answer to problem 7. Function compress should read like
void compress() {
int currentPixel = 0;
int i = 0;
int j = 0;
int length = 0;
while (i < image.length) {
if (image[i] == currentPixel)
length = length + 1;
else {
reducedImage[j] =
length;
j
= j + 1;
currentPixel =
image[i];
length = 1;
}
i = i + 1;
}
reducedImage[j] = length; // store last
count
}