Skip to content

Instantly share code, notes, and snippets.

@jasongorman
Created December 20, 2019 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasongorman/a2a86dd809199d5b590e0800b5eec4fe to your computer and use it in GitHub Desktop.
Save jasongorman/a2a86dd809199d5b590e0800b5eec4fe to your computer and use it in GitHub Desktop.
package com.codemanship.xmastrain;
public class TrainMotion {
private static final int SECONDS_PER_HOUR = 3600;
private static final int METRES_PER_KM = 1000;
private final double acceleration;
private final double topSpeed;
private double velocity;
private double distance;
private final Sensor sensor;
private double lastSensorDistance = 0;
public TrainMotion(double accelerationMs2, double initialVelocityKph, double topSpeedKph, double distanceKm, Sensor sensor) {
this.acceleration = accelerationMs2;
this.velocity = (initialVelocityKph * METRES_PER_KM) / SECONDS_PER_HOUR;
this.topSpeed = (topSpeedKph * METRES_PER_KM) / SECONDS_PER_HOUR;
this.distance = distanceKm * METRES_PER_KM;
this.sensor = sensor;
}
public void move(int timeMilliseconds) {
distance += distanceAdded(timeMilliseconds);
checkForSensorPass();
}
private void checkForSensorPass() {
if (distance - lastSensorDistance >= METRES_PER_KM) {
sensor.passed(distance / METRES_PER_KM, velocity);
lastSensorDistance = distance;
}
}
double velocityAfterAcceleration(int timeMilliseconds) {
velocity = velocity + (acceleration * asSeconds(timeMilliseconds));
if (velocity > topSpeed)
velocity = velocity - (velocity % topSpeed);
return velocity;
}
private int asSeconds(int timeMilliseconds) {
return timeMilliseconds / 1000;
}
double distanceAdded(int timeMilliseconds) {
double avgVelocity = (velocity + velocityAfterAcceleration(timeMilliseconds)) / 2;
return avgVelocity * (asSeconds(timeMilliseconds));
}
double getDistanceTravelledKm() {
return distance / METRES_PER_KM;
}
double getVelocity() {
return velocity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment