You fail to distinguish the cases where the traffic light has turned red and green again a few times before the car arrives. The car may travel at full speed the whole time if the traffic light is green at the time the car arrives, even if it has turned red intermittently while the car was still approaching.
Also, I'm not sure that the expression
ceil(d/v/g+r)
you posted evaluates in the way you expect: for one, I suspect you meant to divide by
(g+r)
, not divide by
g
and then add
r
. Second, the order of evaluation of
(d/v/g)
is not obvious: it could be
((d/v)/g)
or
(d/(v/g))
- which did you intend?
I did not bother to check if either interpretation of your formula would give you the correct result. Instead I will point out how to write code that directly follows the description to the problem and is easy to read and understand:
Step 1: determine the time it takes the car to arrive at the traffic light:
time_to_traffic_light = d/v;
Step 2: determine the number of green-red cycles that have passed before then (the time for one cycle is g+r):
lights_cycle_time = g + r;
number_of_cycles = floor(time_to_traffic_light/lights_cycle_time);
Step 3: determine the time that has passed since the end of the last cycle:
current_cycle_time = time_to_traffic_light - number_of_cycles*lights_cycle_time;
Step 4: check whether the traffic light shows green:
if (current_cycle_time < g)
Step 5: if showing red, determine for how long the car must wait (until the end of the cycle):
else {
wait_time = lights_cycle_time - current_cycle_time;
}
This may not be the shortest code to arrive at the solution, but unless you're participating in a short-code-contest this should never be a criterion. ;-)