FRQ 2012 Post
FRQ 2012 blog post for AP CSA
public class ClimbInfo {
// Initialization of parameters peakName and climbTime not shown
public ClimbInfo(String peakName, int climbTime) {
/* implementation not shown */
}
public String getName() {
/* implementation not shown */
}
public int getTime() {
/* implementation not shown */
}
}
public class ClimbingClub {
private List<ClimbInfo> climbList;
public ClimbingClub() {
climbList = new ArrayList<ClimbInfo>();
}
public void addClimb(String peakName, int climbTime) {
/* part a
ClimbInfo climb = new ClimbInfo(peakName, climbTime);
climbList.add(climb); */
// part b
// Instantiate new ClimbInfo object to store in the ArrayList
ClimbInfo climb = new ClimbInfo(peakName, climbTime);
// Loop through current items of ArrayList
for (int i = 0; i < climbList.size(); i++) {
// Check where the new object should be inserted in order to maintain alphabetical order
if (peakName.compareTo(climbList.get(i).getName()) <= 0) {
// Once the right position is found, insert the new object into that position, and adjust the other elements as needed
// Instantiate temp which will hold the next element that will be moved
ClimbInfo temp = climbList.get(i);
// current marks the element to be currently moved
ClimbInfo current = climb;
for (int j = i; j < climbList.size(); j++) {
// Set current index with the currently moved element
climbList.set(j, current);
// Set current to temp to get ready for the next iteration
current = temp;
// If at last index, add current as a new element to ArrayList
if (j == climbList.size() - 1) {
climbList.add(current);
} else {
// Else, set next element to be moved to temp
temp = climbList.get(j + 1);
}
}
break;
}
}
}
public int distinctPeakNames() {
// Given implementation
if (climbList.size() == 0) {
return 0;
}
ClimbInfo currInfo = climbList.get(0);
String prevName = currInfo.getName();
String currName = null;
int numNames = 1;
for (int k = 1; k < climbList.size(); k++) {
currInfo = climbList.get(k);
currName = currInfo.getName();
// Check if object next to current object has the same peakName
if (prevName.compareTo(currName) != 0) {
numNames++;
prevName = currName;
}
}
return numNames;
// i. This would not work as intended all the time if addClimb stores objects the way they were added,
// because some objects added may have the same name, but are not next to each other and so are not detected
// to be the same by distinctPeakNames.
// ii. This would work as intended if addClimb stores objects in alphabetical order (using peakName), since objects with the same name
// will be placed next to each other, and so will be detected to be the same by distinctPeakNames.
}
}