`AppointmentBook`

is #1 from the from the 2023 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/media/pdf/ap23-frq-comp-sci-a.pdf

## Part (a) `findFreeBlock`

method (original solution)

```
public int findFreeBlock(int period, int duration)
{
for(int startMinute = 0; startMinute <= 59; startMinute++)
{
int endMinute = startMinute + duration - 1;
if(endMinute > 59)
return -1;
boolean isFree = true;
for(int minute = startMinute; minute <= endMinute; minute++)
if( ! isMinuteFree(period, minute) )
isFree = false;
if(isFree)
return startMinute;
}
return -1;
}
```

This could be done in a few ways.

The condition `endMinute > 59`

could be incorporated into the loop. I wrote it this way because it very clearly works.

Some of the code inside the outer loop could be extracted into its own method.

## Part (a) `findFreeBlock`

method (considered solution)

```
public int findFreeBlock(int period, int duration)
{
int freeInARow = 0;
for(int minute = 0; minute <= 59; minute++)
{
if(isMinuteFree(period, minute))
freeInARow++;
else
freeInARow = 0;
if(freeInARow == duration)
return minute - freeInARow + 1;
}
return -1;
}
```

This is a one pass algorithm that keeps track of the number of consecutive free minutes. If at any point, the number of consecutive free minutes equals the requested appointment duration, the start of the current run of free minutes is calculated and returned.

When I did this problem the first time, I was aware that there was a better solution, but it was not immediately obvious. My original solution above is what I wrote under time constraints, because I knew it would work.

The start of the current run could also be stored to avoid the calculation `minute - freeInARow + 1`

.

## Part (b) `makeAppointment`

method

```
public boolean makeAppointment(int startPeriod, int endPeriod,
int duration)
{
for(int period = startPeriod; period <= endPeriod; period++)
{
int startMinute = findFreeBlock(period, duration);
if(startMinute != -1)
{
reserveBlock(period, startMinute, duration);
return true;
}
}
return false;
}
```

## Java files with test code

AppointmentBook.java includes implementations of `isMinuteFree`

and `reserveBlock`

. OneTest.java includes JUnit 5 test code with the examples from the problem. See Running JUnit 5 tests.

AppointmentBook.java

OneTest.java

## 2023 AP CS Exam Free Response Solutions

## Help & comments

Get help from AP CS Tutor Brandon Horn