BoxOfCandy is #4 from the from the 2023 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/media/pdf/ap23-frq-comp-sci-a.pdf

Part (a) moveCandyToFirstRow method

public boolean moveCandyToFirstRow(int col)
{
    if(box[0][col] != null)
        return true;
    
    for(int r = 1; r < box.length; r++)
    {
        if(box[r][col] != null)
        {
            box[0][col] = box[r][col];
            box[r][col] = null;
            return true;
        }
    }
    
    return false;
}

Part (b) removeNextByFlavor method

public Candy removeNextByFlavor(String flavor)
{
    for(int r = box.length - 1; r >= 0; r--)
    {
        for(int c = 0; c < box[0].length; c++)
        {
            if(box[r][c] != null &&
                    box[r][c].getFlavor().equals(flavor))
            {
                Candy selected = box[r][c];
                box[r][c] = null;
                return selected;
            }
        }
    }
    
    return null;
}

I’ve receieved a few comments regarding my use of box[0] instead of box[r]. This is one of the situations in which I advise students to write code differently on the Exam than they would in a real program. box[0] works even if the loop with c is the outer loop. box[r] doesn’t. In a real program, that would be a compile time error. On the Exam, it could cost a point. On the AP CS A Exam, every row of a 2D array is guaranteed to have the same length.

Java files with test code

Candy.java includes a constructor and an implementation of getFlavor. FourTest.java includes JUnit test code with the examples from the problem.

Candy.java
BoxOfCandy.java
FourTest.java

2023 AP CS Exam Free Response Solutions

Additional 2D array resources

Comments

Comment on BoxOfCandy