import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; public class Test { public static void main(String[] args) { FiringTable table = new FiringTable(); // Populate the firing table from emperical data table.put(4.0, 40.0); table.put(4.8, 45.0); table.put(5.1, 45.8); table.put(5.3, 50.0); table.put(5.9, 55.0); System.out.printf("Speed for %f is %f\n", 3.0, table.speedFor(3.0)); // below min System.out.printf("Speed for %f is %f\n", 5.1, table.speedFor(5.1)); // exact match System.out.printf("Speed for %f is %f\n", 5.7, table.speedFor(5.7)); // interpolate System.out.printf("Speed for %f is %f\n", 9.0, table.speedFor(9.0)); // above max } } public class FiringTable { NavigableMap table = new TreeMap<>(); public void put(double distance, double speed) { table.put(distance, speed); } public double speedFor(double distance) { Map.Entry higher = table.ceilingEntry(distance); Map.Entry lower = table.floorEntry(distance); if (lower == null) { // Below min return higher.getValue(); } else if (higher == null) { // above max return lower.getValue(); } else if (lower.getKey() == higher.getKey()) { // Same return lower.getValue(); } else { // somewhere in the middle, so interpolate double interpolateFraction = (higher.getKey() - lower.getKey()) / (distance - lower.getKey()); return lower.getValue() + (higher.getValue() - lower.getValue()) / interpolateFraction; } } }