NumberCube free response answer

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

Review the NumberCube free response problem with AP CS Tutor Brandon Horn.

NumberCube Part (a): getCubeTosses

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;
}

NumberCube Part (b): getLongestRun

public static int getLongestRun(int[] values)
{
  int lengthOfLongestRun = 1;
  int startOfLongestRun = -1;

  int lengthOfCurrentRun = 1;

  for (int i = values.length - 2; i >= 0; i--)
  {
    if (values[i] == values[i + 1])
    {
      lengthOfCurrentRun++;
      if(lengthOfCurrentRun > lengthOfLongestRun)
      {
        lengthOfLongestRun = lengthOfCurrentRun;
        startOfLongestRun = i;
      }
    }
    else
      lengthOfCurrentRun = 0;
  }
		
  return startOfLongestRun;
}

Going backwards eliminates the need to calculate the starting position of the longest run so far.

Get AP CS Help

2009 AP CS Exam Solutions & Explanations

Recommended Practice Problems

Leave a Reply