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.

2011 AP CS Exam Free Response Solutions

Comments

Comment on Sound