ap computer science a 2016 question 3 free response answers code example
Example 1: 2019 ap computer science free response answers
// Part A
public ArrayList<String> getDelimitersList(String[] tokens) {
ArrayList<String> out = new ArrayList<>();
for (String t: tokens) {
if (t.equals(openDel) || t.equals(closeDel))
out.add(t);
}
return out;
}
// Part B
public boolean isBalanced(ArrayList<String> delimiters) {
int open = 0;
int close = 0;
for (String d: delimiters) {
if (d.equals(openDel))
open++;
else if (d.equals(closeDel))
close++;
if (close > open)
return false;
}
return open == close;
}
Example 2: 2019 ap computer science free response answers
// Part A
public static int numberOfLeapYears(int year1, int year2) {
int cnt = 0;
for (int y=year1; y<=year2; y++) {
if (isLeapYear(y))
cnt++;
}
return cnt;
}
// Part B
public static int dayOfWeek(int month, int day, int year) {
int firstDay = firstDayOfYear(year);
int doy = dayOfYear(month, day, year);
return (firstDay + dayOfYear - 1) % 7;
}
Example 3: 2019 ap computer science free response answers
// Part A
public LightBoard(int numRows, int numCols) {
lights = new boolean[numRows][numCols];
for (int r=0; r<numRows; r++)
for (int c=0; c<numCols; c++)
lights[r][c] = Math.random() < 0.4;
}
// Part B
public boolean evaluateLight(int row, int col) {
int onInCol = 0;
for (int r=0; r<lights.length; r++)
if (lights[r][col])
onInCol++;
if (lights[row][col] && onInCol % 2 == 0)
return false;
else if (!lights[row][col] && onInCol % 3 == 0)
return true;
return lights[row][col];
}