2015 Collegeboard FRQ
Question 1
a.
Write a static method arraySum that calculates and returns the sum of the entries in a specified one-dimensional array. The following example shows an array arr1 and the value returned by a call to arraySum.
1
2
3
4
5
6
7
public static int arraySum (int [ ] arr){
int sum = 0;
for (int n : arr){
sum += n;
}
return sum;
}
b.
Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [ r ] [ c ] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.
1
2
3
4
5
6
7
8
9
public static int [ ] rowSums(int [ ] [ ] arr2D){
int[] arr = new int[arr2D.length];
int arrIndex = 0;
for (int[] r : arr){
arr[arrIndex] = arraySum(r);
arrIndex += 1;
}
return arr;
}
c.
Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false.
1
2
3
4
5
6
7
8
9
10
11
public static boolean isDiverse(int [ ] [ ] arr2D){
int[] arrSums = rowSums(arr2D);
for (int i = 0; i< arrSums.length; i++){
for (int j = i+1; j< arrSums.length; j++){
if (arrSums[i] == arrSums[j]){
return false;
}
}
}
return true;
}
Question 2
Write the complete HiddenWord class, including any necessary instance variables, its constructor, and the method, getHint, described above. You may assume that the length of the guess is the same as the length of the hidden word.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class HiddenWord {
String word;
public HiddenWord(String w){
word = w;
}
public String getHint(String guess){
String s="";
for (int i = 0; i <guess.length(); i++){
if (word.charAt(i).equals(guess.charAt(i))){
s += word.charAt(i);
} else if (word.indexOf(guesscharAt(i)) != -1){
s += "+";
} else {
s += "*";
}
}
return s;
}
}
Question 3
a.
Write the SparseArray method getValueAt. The method returns the value of the sparse array element at a given row and column in the sparse array. If the list entries contains an entry with the specified row and column, the value associated with the entry is returned. If there is no entry in entries corresponding to the specified row and column, 0 is returned.
b.
Write the SparseArray method removeColumn. After removing a specified column from a sparsearray: