11.04.2023, 06:12
1. prices must be a table where key is hour (0..23) and value is price. The resulting minhour variable is the first hour of the 4 hour period with the lowest prices.
2. For night prices use this, adjust night hours as needed (22 to 5 inclusive in this example).
Code:
minsum = math.huge
minhour = 0
step = 4
for hour = 0, 24 - step do
sum = 0
for i = hour, hour + step - 1 do
sum = sum + prices[ i ]
end
if sum < minsum then
minsum = sum
minhour = hour
end
end
log(minhour)
2. For night prices use this, adjust night hours as needed (22 to 5 inclusive in this example).
Code:
for hour = 0, 23 do
if hour >= 22 or hour <= 5 then
nightprices[ #nightprices + 1 ] = {
hour = hour,
price = prices[ hour ]
}
end
end
table.sort(nightprices, function(a, b)
return a.price < b.price
end)
for i = 1, 4 do
item = nightprices[ i ]
log(item.hour, item.price)
end