The Sound problem from the 2011 AP Computer Science Exam is typical of free response problems that test arrays. The problem requires you to find and modify elements that exceed a given limit.

Sound is #1 from the from the 2011 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/apc/ap11_frq_comp_sci_a.pdf

Part (a) limitAmplitude method

public int limitAmplitude(int limit)
{
    int numChanges = 0;

    for (int i = 0; i < samples.length; i++)
    {
        if (samples[i] > limit)
        {
            samples[i] = limit;
            numChanges++;
        }
        else if (samples[i] < -limit)
        {
            samples[i] = -limit;
            numChanges++;
        }
    }

    return numChanges;
}

Part (b) trimSilenceFromBeginning method

public void trimSilenceFromBeginning()
{
    int leadingZeros = 0;

    // precondition guarantees at least 1 non-zero element
    // so no need to check for out of bounds
    while(samples[leadingZeros] == 0)
        leadingZeros++;

    int[] withoutLeadingZeros = new int[samples.length - leadingZeros];

    for(int i = leadingZeros; i < samples.length; i++)
        withoutLeadingZeros[i - leadingZeros] = samples[i];

    samples = withoutLeadingZeros;
}

The for loop uses i as the index where the element is now. I know where the element is going based on where it is now, so this is my preferred option.

If you find it easier, you can maintain separate indexes for samples and withoutLeadingZeros.

Part (b) trimSilenceFromBeginning method (alternate solution)

public void trimSilenceFromBeginning()
{
    int leadingZeros = 0;

    while (samples[leadingZeros] == 0)
        leadingZeros++;

    int[] withoutLeadingZeros = new int[samples.length - leadingZeros];
    
    int newIndex = 0;

    for (int oldIndex = leadingZeros; oldIndex < samples.length; oldIndex++)
    {
        withoutLeadingZeros[newIndex] = samples[oldIndex];
        newIndex++;
    }

    samples = withoutLeadingZeros;
}

This solution declares, initializes, updates, and uses newIndex instead of calculating the index in withoutLeadingZeros based on the index in samples. This is a common technique. It is especially useful when the calculation is challenging or if it is easy to make an off by one error.

2011 AP CS Exam Free Response Solutions

Comments

Comment on Sound