Created
March 22, 2023 04:13
-
-
Save roshane/ec9cd2ccb4cf3334025c369abb4593cb to your computer and use it in GitHub Desktop.
Booking Algo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.*; | |
import java.time.format.*; | |
import java.util.*; | |
public class BookingAlgorithm { | |
public static void main(String[] args) { | |
// Example inputs | |
LocalDateTime startTime = LocalDateTime.of(2023, 3, 22, 9, 0); | |
LocalDateTime endTime = LocalDateTime.of(2023, 3, 22, 17, 0); | |
Duration bookDuration = Duration.ofMinutes(60); | |
// Call the algorithm to get the booked time slot | |
LocalDateTime bookedStartTime = bookTimeSlot(startTime, endTime, bookDuration); | |
// Print the booked time slot | |
if (bookedStartTime != null) { | |
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy hh:mm a"); | |
String startTimeStr = formatter.format(bookedStartTime); | |
String endTimeStr = formatter.format(bookedStartTime.plus(bookDuration)); | |
System.out.println("Booked time slot: " + startTimeStr + " - " + endTimeStr); | |
} else { | |
System.out.println("Could not book a time slot."); | |
} | |
} | |
public static LocalDateTime bookTimeSlot(LocalDateTime startTime, LocalDateTime endTime, Duration bookDuration) { | |
// Check if there is enough time for the booking | |
if (Duration.between(startTime, endTime).compareTo(bookDuration) < 0) { | |
return null; // Not enough time for booking | |
} | |
// Generate a list of all available time slots | |
List<LocalDateTime> availableTimeSlots = new ArrayList<>(); | |
LocalDateTime currTime = startTime; | |
while (currTime.plus(bookDuration).isBefore(endTime) || currTime.plus(bookDuration).isEqual(endTime)) { | |
availableTimeSlots.add(currTime); | |
currTime = currTime.plusMinutes(1); | |
} | |
// Check if any existing bookings conflict with the available time slots | |
// This is just a placeholder for a more advanced algorithm that checks for conflicting bookings | |
List<LocalDateTime> conflictingBookings = new ArrayList<>(); | |
for (LocalDateTime booking : conflictingBookings) { | |
availableTimeSlots.removeIf(slot -> booking.plus(bookDuration).isAfter(slot) && booking.isBefore(slot.plus(bookDuration))); | |
} | |
// Book the first available time slot | |
if (!availableTimeSlots.isEmpty()) { | |
return availableTimeSlots.get(0); | |
} else { | |
return null; // No available time slots | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment