Introduction
I created solutions to these as an exercise, trying to use methods I wasn't familiar with. Simpler solutions with methods inside of the AP CSA subset are located here.
These solutions may have issues; you can contact me with a description if you would like them fixed.
Questions
CollegeBoard® released the AP Computer Science A Free Response Questions on AP Central, accessible here.
Question 1 (DogWalker)
public int walkDogs(int hour) {
int available = company.numAvailableDogs(hour);
int dogsToWalk = Math.min(available, maxDogs);
company.updateDogs(hour, dogsToWalk);
return dogsToWalk;
}
public int dogWalkShift(int startHour, int endHour) {
return java.util.stream.IntStream.rangeClosed(startHour, endHour)
.map(h -> {
int walked = walkDogs(h);
int earnings = walked * 5;
if (walked == maxDogs || (h >= 9 && h <= 17)) {
earnings += 3;
}
return earnings;
})
.sum();
}
Question 2 (SignedText)
public class SignedText {
private final String first;
private final String last;
private final String signature;
public SignedText(String firstName, String lastName) {
this.first = firstName;
this.last = lastName;
this.signature = first.isEmpty() ? last : first.charAt(0) + "-" + last;
}
public String getSignature() {
return signature;
}
public String addSignature(String text) {
if (text.startsWith(signature)) {
return text.substring(signature.length()) + signature;
}
if (text.endsWith(signature)) {
return text;
}
return text + signature;
}
}
Question 3 (Round.java)
public Round(String[] names) {
competitorList = new ArrayList<>(names.length);
java.util.stream.IntStream.range(0, names.length)
.forEach(i -> competitorList.add(new Competitor(names[i], i + 1)));
}
public ArrayList<Match> buildMatches() {
int size = competitorList.size();
ArrayList<Match> matches = new ArrayList<>();
java.util.stream.IntStream.range(0, size / 2)
.forEach(k -> {
int left = (size % 2 == 1) ? k + 1 : k;
int right = size - 1 - k;
if (left < right) {
matches.add(new Match(competitorList.get(left), competitorList.get(right)));
}
});
return matches;
}
Question 4 (SumOrSameGame.java)
public SumOrSameGame(int numRows, int numCols) {
java.util.Random rand = new java.util.Random();
puzzle = new int[numRows][numCols];
java.util.Arrays.setAll(puzzle, r -> {
int[] row = new int[numCols];
java.util.Arrays.setAll(row, c -> 1 + rand.nextInt(9));
return row;
});
}
public boolean clearPair(int row, int col) {
int value = puzzle[row][col];
if (value == 0) {
return false;
}
for (int r = row; r < puzzle.length; r++) {
for (int c = 0; c < puzzle[r].length; c++) {
if (r == row && c == col) {
continue;
}
int other = puzzle[r][c];
if (other != 0 && (other == value || other + value == 10)) {
puzzle[row][col] = 0;
puzzle[r][c] = 0;
return true;
}
}
}
return false;
}