scrambleWord and scrambleOrRemove is #1 from the from the 2014 AP Computer Science A Free Response problems.
2014 AP CS A Free Response (Internet Archive)
Part (a) scrambleWord method
public static String scrambleWord(String word)
{
String scrambledWord = word;
int i = 1;
while(i < scrambledWord.length())
{
if("A".equals(scrambledWord.substring(i - 1, i)) &&
! "A".equals(scrambledWord.substring(i, i + 1)))
{
scrambledWord =
scrambledWord.substring(0, i - 1) +
scrambledWord.substring(i, i + 1) +
"A" +
scrambledWord.substring(i + 1);
i += 2;
}
else
i++;
}
return scrambledWord;
}
Although String objects are immutable, it is possible to pretend that they are mutable by making a new String object and setting the existing variable to point to it. This approach makes this problem much simpler.
See Strings on the AP CS A Exam for an explanation of String methods and String concatenation.
An alternative approach is to build a new String by concatenating parts of the existing String. This is difficult here, especially with respect to the end of the new String.
A recursive approach is also reasonable here (see below).
Part (a) scrambleWord (recursive approach)
public static String scrambleWord(String word)
{
if(word.length() <= 1)
return word;
if(word.substring(0, 1).equals("A") && ! word.substring(1, 2).equals("A"))
return word.substring(1, 2) + "A" + scrambleWord(word.substring(2));
else
return word.substring(0, 1) + scrambleWord(word.substring(1));
}
Part (a) scrambleWord (alternate approach)
public static String scrambleWord(String word)
{
String scrambled = "";
int i = 0;
while(i < word.length() - 1)
{
if(word.substring(i, i + 1).equals("A") && ! word.substring(i + 1, i + 2).equals("A"))
{
scrambled += word.substring(i + 1, i + 2);
scrambled += "A";
i += 2;
}
else
{
scrambled += word.substring(i, i + 1);
i++;
}
}
if(scrambled.length() < word.length())
scrambled += word.substring(word.length() - 1);
return scrambled;
}
This approach builds a new string from scratch rather than pretending to mutate the existing string.
Part (b) scrambleOrRemove method
public static void scrambleOrRemove(List<String> wordList)
{
for(int i = wordList.size() - 1; i >= 0; i--)
{
String scrambled = scrambleWord(wordList.get(i));
if(wordList.get(i).equals(scrambled))
wordList.remove(i);
else
wordList.set(i, scrambled);
}
}
See ArrayList practice for details on adding to and removing from an ArrayList within a loop.
2014 AP CS Exam Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn