scrambleWord and scrambleOrRemove free response problem from the 2014 AP Computer Science A Exam.
This problem is #1 from the from the 2014 AP Computer Science A Free Response problems.
http://media.collegeboard.com/digitalServices/pdf/ap/ap14_frq_computer_science_a.pdf
Part (a) – scrambleWord
public static String scrambleWord(String word)
{
for(int i = 1; i < word.length(); i++)
if("A".equals(word.substring(i-1, i)) &&
! "A".equals(word.substring(i, i+1)))
{
word = word.substring(0, i-1) +
word.substring(i, i+1) +
word.substring(i-1, i) +
word.substring(i+1);
i++;
}
return word;
}
Part (b) – scrambleOrRemove
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);
}
}
Hi is it okay if I made mine recursive?
On the AP test I had a couple cases for a but I’m sure it worked
A correct recursive solution would receive full credit.
Hello im just wondering if there would be point reductions for using “=” or “!=” instead of the “equals”
While I don’t have the scoring guidelines there is typically a penalty for incorrectly using
==
to compareString
objects. If you obtainedchar
types usingcharAt
then==
would be correct.is the “else wordList.set(i, scrambled);” necessary?
Yes.
String
objects are immutable. Scrambling the word obtained from the list does not change the word in the list. theset
call is what actually changes the list.For part B, was it necessary to go backwards in the loop?
You must avoid skipping the next element each time you remove an element from the list. You can do that by going backwards or by decrementing your loop control variable every time you remove an element.
I believe your solution to part B is incorrect. You must decrement i after you call wordList.remove(i), otherwise, the new element in position i will not be evaluated.
My loop traverses
wordList
backwards. The elements that are shifted by the call toremove
have already been processed. If the loop traversed the list starting at index 0 a decrement would be necessary.Whether or not the element at the index is removed, the index decremement will move to the next (lower) index and test that. If an element is removed, the element that was at an index one greater will slide into the index of the element that was just removed. This will not matter, because the index of the
for
loop will already be ahead (one less numerically because we are decrementing) of the elements that are sliding because of removals. A way that may be easier to comprehend is usingfor(int i = 0; i < wordList.size(); )
and only incrementing when the tested element is not removed. Then thefor
loop would only test the 0 index and let new elements slide in as “bad” ones are removed. If the element isn’t removed, increment and change the “test” index to one larger and let more slide in from there.Hope this clarifies!