public class AppointmentBook
{
private boolean[][] freePeriod = new boolean[9][60];
public AppointmentBook()
{
for (int i = 1; i < 9; i++) // Only uses rows 1 to 8
for (int j = 0; j < 60; j++)
freePeriod[i][j] = true;
}
/**
* Returns true if minute in period is available for an appointment and
* returns false otherwise
* Preconditions: 1 <= period <= 8; 0 <= minute <= 59
*/
private boolean isMinuteFree( int period, int minute )
{
return freePeriod[period][minute];
}
/**
* Marks the block of minutes that starts at startMinute in period and
* is duration minutes long as reserved for an appointment
* Preconditions: 1 <= period <= 8; 0 <= startMinute <= 59;
* 1 <= duration <= 60
*/
public void reserveBlock( int period, int startMinute, int duration )
{
for ( int j = startMinute; j < startMinute+duration; j++)
freePeriod[period][j] = false;
}
/**
* Searches for the first block of duration free minutes during period,
* as described in part (a).
* Returns the first minute in the block if such a block is found or
* returns -1 if no such block is found.
* Preconditions: 1 <= period <= 8; 1 <= duration <= 60
*/
public int findFreeBlock( int period, int duration )
{
/* to be implemented in part (a) */
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;
//return -1; // Change when writing answer
}
/**
* Searches periods from startPeriod to endPeriod, inclusive, for a block
* of duration free minutes, as described in part (b).
* If such a block is found, calls reserveBlock to reserve the block
* of minutes and returns true; otherwise returns false.
* Preconditions: 1 <= startPeriod <= endPeriod <= 8; 1 <= duration <= 60
*/
public boolean makeAppointment(int startPeriod, int endPeriod, int duration)
{
/* to be implemented in part (b) */
for(int period = startPeriod; period <= endPeriod; period++)
{
int startMinute = findFreeBlock(period, duration);
if(startMinute != -1)
{
reserveBlock(period, startMinute, duration);
return true;
}
}
return false;
//return false; // Change when writing answer
}
public String toString(int period)
{
boolean currState = freePeriod[period][0];
int initMin = 0;
int currMin = 1;
String out = "";
while ( currMin <= 59 )
{
if ( freePeriod[period][currMin] != currState )
{
out = out + period + "\t"
+ initMin + "-" + (currMin-1)
+ " (" + (currMin-initMin) + " minutes)\t"
+ (currState ? "Yes" : "No") + "\n";
initMin = currMin;
currState = freePeriod[period][currMin];
}
if ( currMin == 59 )
{
out = out + period + "\t"
+ initMin + "-" + (currMin)
+ " (" + (currMin-initMin+1) + " minutes)\t"
+ (currState ? "Yes" : "No") + "\n";
}
currMin++;
}
return out;
}
}
|