Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MorphingDragon

macrumors 603
Original poster
Mar 27, 2009
5,159
6
The World Inbetween
I'm making a program to hold a diary for an HCI assignment and I'm having issues for checking when two appointments might have a collision.

The class holds appointments as two (Java) Calendars that hold when the appointment starts and finishes.

I have a method to see if a appointment might have a time collision with another appointment. But I'm having an issue where say, I have an appointment from 1-2pm, and another from 2pm-2:30, the method returns saying there is a collision.

This is my current code:
Code:
	/**
	 * This method checks to see if the appointment collides with the
	 * given appointment.
	 */
	public boolean checkCollision(Appointment o) {
                // Get UNIX time
		long start1 = start_.getTimeInMillis();
		long start2 = o.start_.getTimeInMillis();
		long end1 = finish_.getTimeInMillis();
		long end2 = o.finish_.getTimeInMillis();

		// Return result
		return ((start1 >= start2 && start1 <= end2)
				|| (end1 >= start2 && end1 <= end2) || (start1 <= start2 && end1 >= end2));
	}
 
Your code is including the end-point of an appointment in the appointment's interval. So in your example, your code considers 1-2 and 2-2:30 to collide because 2:00 is occupied by both appointments. Typically the end-point of an appointment is excluded from the an appointment's interval. With this arrangement, your example won't collide because the 1-2 appointment will go up to but won't include 2:00, and so 2:00 is only occupied by the 2-2:30 appointment.

I've leave it you to modify your code.
 
I've leave it you to modify your code.

This is my solution that seems to work according to my JUnit tests. -1 was much easier than trying to rework the comparison mess.

Code:
	/**
	 * This method checks to see if the given appointment collides with the
	 * current appointment.
	 */
	public boolean checkCollision(Appointment o) {
		// Get UNIX time
		long start1 = start_.getTimeInMillis();
		long start2 = o.start_.getTimeInMillis();
		long end1 = finish_.getTimeInMillis() - 1;
		long end2 = o.finish_.getTimeInMillis() - 1;

		// Return result
		return ((start1 >= start2 && start1 <= end2)
				|| (end1 >= start2 && end1 <= end2) || (start1 <= start2 && end1 >= end2));
	}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.