Java Puzzle 3: Car - Part 2
Mar 03, 2012Here's the solution to the first part of the car puzzle. And, -- for those who haven't solved part one and seen it yet -- we'll toughen up the challenge for the second round. Here's the method it's all about:
How do we make this go over the speed limit?
The flaw is in the check of the acceleration: it checks if it's too high, but it forgot to check if it's too low. Put your gearbox in reverse, push the pedal to the metal (Integer.MIN_VALUE
), and the speedometer will wrap around.
First we give it a little tap to set speed
to -1
. Then we push it all the way: the check if Integer.MIN_VALUE > 99
passes, giving us -1 + Integer.MIN_VALUE
. That causes an underflow, putting the car in its real top speed: Integer.MAX_VALUE
.
Let's avoid that kind of mistake, by checking the resulting speed instead of the acceleration:
Can you still break the speed limit in this car?
The solutions (yes, that's plural) to this are not always very reliable. How good they work may depend on the environment they're running in. But with some tweaks and the right approach, it is possible to build a solution that should work all the time in practice without taking any significant time. 175 people solved the first part, but so far only 11 broke this part. If that doesn't scare you off, good luck! You can try out your solution on this ugly site.
The solutions will follow tomorrow are available.