The `NumberCube`

problem from the 2009 AP Computer Science Exam is typical of free response problems that test arrays.

`NumberCube`

is #1 from the 2009 AP Computer Science Free Response.

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

## Part (a) `getCubeTosses`

method

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

## Part (b) `getLongestRun`

method

```
public static int getLongestRun(int[] values)
{
int inARow = 1;
int maxInARow = 1;
int startOfMaxInARow = -1;
for (int i = values.length - 2; i >= 0; i--)
{
if (values[i] == values[i + 1])
{
inARow++;
if(inARow > maxInARow)
{
maxInARow = inARow;
startOfMaxInARow = i;
}
}
else
inARow = 1;
}
return startOfMaxInARow;
}
```

`inARow`

stores the the number of visited consecutive occurrences of `values[i]`

. `i`

starts at `values.length - 2`

(skips the last element). `inARow`

starts at `1`

to account for the skipped element. `inARow`

is reset to `1`

at the end of each run to account for the value at `i`

.

`maxInARow`

stores the highest known number of consecutive occurrences of a value. `maxInARow`

starts at `1`

for the same reason `inARow`

starts at `1`

.

`startOfMaxInARow`

stores the starting index of the longest known run of occurrences of a value, or `-1`

if no run is known. A run must have a length `>= 2`

. If `maxInARow`

stores `1`

, as it is does initially, no run has yet been identified.

The loop runs backwards to avoiding needing to calculate the starting position of the longest run so far. The loop skips the last element so the conditional statement can access `values[i + 1]`

.

This is a variation of find the minimum or maximum. `maxInARow`

starts at `1`

since the loop skips an element. The length of each run is compared against the length of the longest known run.

## Additional resources

## 2009 AP CS Exam Free Response Solutions

- StockpileCritter Free Response Solution
- BatteryCharger Free Response Solution
- TileGame Free Response Solution

## Help & comments

Get help from AP CS Tutor Brandon Horn