Java Puzzle 3: Car - Part 2

Mar 03, 2012

Here'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:

    public synchronized void accelerate(int acceleration) {
        if (acceleration > MAX_SPEED - speed)
            crash();
        else
            speed += acceleration;
    }

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.

Car car = new Car();
car.accelerate(-1);
car.accelerate(Integer.MIN_VALUE);
car.vroom();

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:

package car;

public final class Car {
    private final int MAX_SPEED = 100;

    private int speed = 0;

    public synchronized void accelerate(int acceleration) {
        speed += acceleration;
        if (speed > MAX_SPEED)
            crash();
    }

    public synchronized void crash() {
        speed = 0;
    }

    public synchronized void vroom() {
        if (speed > MAX_SPEED * 10) {
            // The goal is to reach this line
            System.out.println("Vroom!");
        }
    }
}

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.