Question 141
The ClubAttendance class stores the number of students who attended an after-school club on each recorded meeting day. The declaration below shows the instance variable and method headers.
public class ClubAttendance
{
private int[] attendance;
public ClubAttendance(int[] data)
{
attendance = data;
}
public int countBusyDays(int minStudents)
{ /* to be implemented in part (a) */ }
public int firstLongRun(int minStudents, int runLength)
{ /* to be implemented in part (b) */ }
}
Part (a). Write the method countBusyDays, which returns the number of entries in attendance that are greater than or equal to minStudents.
For example, if attendance contains {12, 18, 16, 9, 18, 20}, then countBusyDays(18) returns 3.
Part (b). Write the method firstLongRun, which returns the starting index of the first sequence of runLength consecutive entries in attendance that are each greater than or equal to minStudents. If no such sequence exists, the method returns -1.
For example, if attendance contains {12, 18, 16, 19, 20, 10}, then firstLongRun(16, 3) returns 1 because the first run of three qualifying values begins at index 1. The run {18, 16, 19} qualifies, and no earlier run does.
Main Solution
Sample Solution
public int countBusyDays(int minStudents)
{
int count = 0;
for (int i = 0; i < attendance.length; i++)
{
if (attendance[i] >= minStudents)
{
count++;
}
}
return count;
}
public int firstLongRun(int minStudents, int runLength)
{
for (int start = 0; start <= attendance.length - runLength; start++)
{
boolean good = true;
for (int k = 0; k < runLength; k++)
{
if (attendance[start + k] < minStudents)
{
good = false;
}
}
if (good)
{
return start;
}
}
return -1;
}
Scoring (9 pts): Part (a): +1 correct traversal, +1 correct comparison >=, +1 increments count correctly, +1 returns the count. Part (b): +1 checks every possible starting index, +1 uses a nested check of runLength entries, +1 rejects runs containing any nonqualifying entry, +1 returns the first valid starting index, +1 returns -1 when no run exists.
Answer images

