Sponsored
Sponsored
This approach involves simulating the process: for each customer, determine when their order can start based on the current time (when the previous order finishes) and calculate their waiting time.
You'll need to track the current time and update it as each order is processed.
Time Complexity: O(n) because we iterate over the customers.
Space Complexity: O(1) as we use a constant space.
1import java.util.List;
2
3public class AverageWaitingTime {
4 public static double averageWaitingTime(List<int[]> customers) {
5 int currentTime = 0;
6 double totalWaitingTime = 0.0;
7 for(int[] customer : customers) {
8 int arrival = customer[0];
9 int time = customer[1];
10 currentTime = Math.max(currentTime, arrival) + time;
11 totalWaitingTime += currentTime - arrival;
12 }
13 return totalWaitingTime / customers.size();
14 }
15
16 public static void main(String[] args) {
17 List<int[]> customers = List.of(new int[]{1, 2}, new int[]{2, 5}, new int[]{4, 3});
18 System.out.printf("%.5f\n", averageWaitingTime(customers));
19 }
20}
This Java solution uses a List to manage input data and computes the average waiting time by checking when each customer can be served compared to the current idle time of the chef.
In scenarios with dynamic restaurant workflows, using event simulation with a priority queue could be beneficial. Here, though all customers wait in order, this method can plan for potential future complexity.
This approach is more efficient when prioritizing different jobs based on arrival or cooking time in expanded contexts.
Time Complexity: O(n log n) due to priority queue operations.
Space Complexity: O(n) for the queue population.
1#include <iostream>
2#include <vector>
3#include <queue>
4#include <utility>
5
6float averageWaitingTime(std::vector<std::pair<int,int>>& customers) {
7 int currentTime = 0;
float totalWaitingTime = 0.0;
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq;
for(auto& customer : customers) {
pq.push(customer);
}
while (!pq.empty()) {
auto customer = pq.top(); pq.pop();
int arrival = customer.first;
int time = customer.second;
currentTime = std::max(currentTime, arrival) + time;
totalWaitingTime += currentTime - arrival;
}
return totalWaitingTime / customers.size();
}
int main() {
std::vector<std::pair<int, int>> customers = {{1,2},{2,5},{4,3}};
std::cout << std::fixed << std::setprecision(5) << averageWaitingTime(customers) << std::endl;
return 0;
}
This C++ solution utilizes a priority queue, simulating an event-driven strategy. Although it prioritizes emissions less efficiently for this fixed input, the template demonstrates adaptability for more assorted queues and orders beyond the current sorting constraints.