SumOrSameGame
is #4 from the from the 2025 AP Computer Science A Free Response problems.
https://apcentral.collegeboard.org/media/pdf/ap25-frq-computer-science-a.pdf
Part (a) SumOrSameGame
constructor
public SumOrSameGame(int numRows, int numCols)
{
puzzle = new int[numRows][numCols];
for(int r = 0; r < puzzle.length; r++)
for(int c = 0; c < puzzle[0].length; c++)
puzzle[r][c] = (int) (Math.random() * 9) + 1;
}
The first line, in which the instance variable puzzle
is initialized, is often written incorrectly (ex: int[] puzzle = ...
) or missed entirely. Initializing the instance variable to point to a new (in this case 2D) array is different than setting values within the array.
See Generate random numbers with Math.random() for a technique to generate random numbers in precise ranges and ensure correctness.
Part (b) clearPair
method
public boolean clearPair(int row, int col)
{
for(int r = row; r < puzzle.length; r++)
{
for(int c = 0; c < puzzle[0].length; c++)
{
if(r != row || c != col)
{
if(puzzle[row][col] == puzzle[r][c] ||
puzzle[row][col] + puzzle[r][c] == 10)
{
puzzle[row][col] = 0;
puzzle[r][c] = 0;
return true;
}
}
}
}
return false;
}
Java files with test code
SumOrSameGame.java
FourTest.java
2025 AP CS Exam Free Response Solutions
Additional resources
- Intro to 2D arrays
- Treating a 2D array as an array of 1D arrays
- 2D array exercises
- Flight free response
Help & comments
Get help from AP CS Tutor Brandon Horn
See an error? Question? Please comment below.
2025-05-10 comment
Anonymous
For part B do you have to use a nested for loop since I just checked all of the ones around it not used a for
loop.
Response
One of the conditions in the problem description is, “The row index of the second element is greater than or equal to the parameter row
.”
This means all elements in the same row as row
(other than the element at [row][col]
) and all elements in subsequent rows must be checked. It is possible to do this with a single loop, though the nested solution is easier to write and much more common.
If “… all of the ones around it…” refers to elements adjacent to the element at [row][col]
, that does not meet the requirements.