The RouteCipher
problem from the 2011 AP Computer Science Exam is typical of free response problems that test 2 dimensional arrays. The problem requires you to traverse the array in row major order, which is most easily accomplished with nested for
loops.
RouteCipher
is #4 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) fillBlock
method
private void fillBlock(String str)
{
int strIndex = 0;
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numCols; c++)
{
if (strIndex >= str.length())
letterBlock[r][c] = "A";
else
letterBlock[r][c] = str.substring(strIndex, strIndex + 1);
strIndex++;
}
}
}
See 2D array exercises for additional traversals and other challenges.
Part (a) fillBlock
method (alternate solution)
private void fillBlock(String str)
{
for (int i = 0; i < numRows * numCols; i++)
{
if (i >= str.length())
letterBlock[i / numCols][i % numCols] = "A";
else
letterBlock[i / numCols][i % numCols] = str.substring(i, i + 1);
}
}
Part (b) encryptMessage
method
public String encryptMessage(String message)
{
String cipherText = "";
int mIndex = 0;
while(mIndex < message.length())
{
fillBlock(message.substring(mIndex)); // ignores extra characters
cipherText += encryptBlock();
mIndex += numRows * numCols;
}
return cipherText;
}
Part (b) encryptMessage
method (alternate solution 1)
public String encryptMessage(String message)
{
String cipherText = "";
String mRemaining = message;
while (mRemaining.length() > 0)
{
fillBlock(mRemaining); // ignores extra characters
cipherText += encryptBlock();
if(mRemaining.length() > numRows * numCols)
mRemaining = mRemaining.substring(numRows * numCols);
else
mRemaining = "";
}
return cipherText;
}
Part (b) encryptMessage
method (alternate solution 2)
public String encryptMessage(String message)
{
String cipherText = "";
for(int i = 0; i < message.length(); i += numRows * numCols)
{
fillBlock(message.substring(i));
cipherText += encryptBlock();
}
return cipherText;
}
This is the same as the first solution except with a for
loop.
2011 AP CS Exam Free Response Solutions
- Sound Free Response Solution
- AttractiveCritter Free Response Solution
- FuelDepot Free Response Solution
Additional resources for 2D arrays
- Intro to 2D arrays
- 2D array exercises
- Mazer free response
- Droppy free response
- Flight free response
- MatrixManipulator exercise
Help & comments
Get help from AP CS Tutor Brandon Horn