2009 AP CSA FRQ 1: NumberCube - Solution

2009 AP CSA FRQ 1: NumberCube

Topic: Arrays & Run Detection

Skills: Array creation, random number simulation, run detection algorithm

Unit: Unit 4 (Data Collections) (2025-2026 AP CSA)

Points: 9 | Time: ~22 minutes

Part (a)

Write the getCubeTosses method that fills an array with random cube tosses.

Try First! Attempt before viewing solution.

Solution

public static int[] getCubeTosses(NumberCube cube, int numTosses)
{
    int[] tosses = new int[numTosses];
    for (int i = 0; i < numTosses; i++)
    {
        tosses[i] = cube.toss();
    }
    return tosses;
}

Part (b)

Write the getLongestRun method that finds the starting index of the longest run of consecutive equal values.

Solution

public static int getLongestRun(int[] values)
{
    int maxRunStart = -1;
    int maxRunLength = 0;
    int currentStart = 0;
    int currentLength = 1;
    
    for (int i = 1; i < values.length; i++)
    {
        if (values[i] == values[i - 1])
        {
            currentLength++;
        }
        else
        {
            if (currentLength > 1 && currentLength > maxRunLength)
            {
                maxRunStart = currentStart;
                maxRunLength = currentLength;
            }
            currentStart = i;
            currentLength = 1;
        }
    }
    
    // Check last run
    if (currentLength > 1 && currentLength > maxRunLength)
    {
        maxRunStart = currentStart;
    }
    
    return maxRunStart;
}

Key Concepts

✓ Array creation with new int[size]
✓ Run detection requires tracking start and length
✓ Compare adjacent elements: values[i] == values[i-1]
✓ Check final run after loop ends

Common Mistakes

Forgetting to check the last run after the loop
Off-by-one errors in run start index
Not handling case with no runs (return -1)
Starting loop at 0 instead of 1 for adjacent comparison

Official Resources

Author: Tanner Crow - AP CS Teacher, 11+ years

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]