Created
February 28, 2020 16:57
-
-
Save swalberg/b4917f9b3963e8f69a9834fb54d0f9e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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<Double, Double> table = new TreeMap<>(); | |
public void put(double distance, double speed) { | |
table.put(distance, speed); | |
} | |
public double speedFor(double distance) { | |
Map.Entry<Double, Double> higher = table.ceilingEntry(distance); | |
Map.Entry<Double, Double> 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment