A car moves along a straight path composed of n segments. Segments start at waypoint i-1 and end at waypoint i. The car starts at t=0 and at waypoint 0. The car travels along the segment at a constant speed, s_i being the car’s speed for that specific segment. The car’s speed for that particular segment is bounded by s_i_min and s_i_max. The length of a segment is denoted by d_i. The time that the car arrives at a waypoint is denoted t_i, and the car must arrive at a waypoint between t_i_min and t_i_max. The car consumes fuel at a rate dependant on the car’s speed.

Given the data d (segment lengths), s_min, s_max, t_min, t_max, and the fuel consumption function; chose the speeds that the car travels along for each segment in an optimal manner in which the total fuel consumed is minimized.

```
local segments = {}
local segment = {}
local function fuelConsumptionFunction(speed)
-- Rate at which fuel is used
return (speed^2) + (5*speed) + 15
end
function bounds(x, a, b)
return (x >= a and x <= b)
end
function chooseSpeeds(segments, fuel_consumption_func)
for i,segment in pairs(segments) do
segment.s = (math.random() * (segment.s_max - segment.s_min)) + segment.s_min -- Write algorithm to minimize the fuel consumption total
-- This is just an example optimization function that randomly generates valid speeds
end
end
function segment:new(d, t_min, t_max, s_min, s_max, s)
local instance = {}
instance.d = d
instance.t_min = t_min
instance.t_max = t_max
instance.s_min = s_min
instance.s_max = s_max
instance.s = s
setmetatable(instance, self)
self.__index = self
return instance
end
function calculate(segments, fuel_consumption_func)
local time_arrival = 0
local total_fuel_usage = 0
for i,segment in pairs(segments) do
local time_arrival_delta = segment.d / segment.s
time_arrival = time_arrival + time_arrival_delta
local fuel_use_segment = time_arrival_delta * fuel_consumption_func(segment.s)
assert(bounds(segment.s, segment.s_min, segment.s_max), "speed bounds violated: " .. i)
assert(bounds(time_arrival, segment.t_min, segment.t_max), "time bounds violated: " .. i)
total_fuel_usage = total_fuel_usage + fuel_use_segment
end
return total_fuel_usage
end
segments[1] = segment:new(1.9501, 1.0809, 4.6528, 0.7828, 1.9624, nil)
segments[2] = segment:new(1.2311, 2.7265, 6.5147, 0.6235, 1.6036, nil)
segments[3] = segment:new(1.6068, 3.5118, 7.5178, 0.7155, 1.6439, nil)
segments[4] = segment:new(1.4860, 5.3038, 9.7478, 0.5340, 1.5641, nil)
segments[5] = segment:new(1.8913, 5.4516, 9.0641, 0.6329, 1.7194, nil)
math.randomseed(30)
chooseSpeeds(segments, fuelConsumptionFunction)
local consumed_fuel = calculate(segments, fuelConsumptionFunction)
print(consumed_fuel) -- Write the optimal function chooseSpeeds so that the consumed_fuel is minimized!
```