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.
1using System;
2using System.Collections.Generic;
3
4public class AverageWaitingTime {
5 public static double ComputeAverageWaitingTime(List<int[]> customers) {
6 int currentTime = 0;
7 double totalWaitingTime = 0.0;
8 foreach(var customer in customers) {
9 int arrival = customer[0];
10 int time = customer[1];
11 currentTime = Math.Max(currentTime, arrival) + time;
12 totalWaitingTime += currentTime - arrival;
13 }
14 return totalWaitingTime / customers.Count;
15 }
16
17 public static void Main() {
18 var customers = new List<int[]> { new int[] {1, 2}, new int[] {2, 5}, new int[] {4, 3} };
19 Console.WriteLine(ComputeAverageWaitingTime(customers).ToString("F5"));
20 }
21}
This C# solution manages data using a List of integer arrays. It calculates the average waiting time by adjusting the current time after each customer's order is processed, and then averaging.
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.