-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathInterpolatingTreeMap.java
80 lines (68 loc) · 2.42 KB
/
InterpolatingTreeMap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.team254.lib.util;
import java.util.Map;
import java.util.TreeMap;
/**
* Interpolating Tree Maps are used to get values at points that are not defined by making a guess from points that are
* defined. This uses linear interpolation.
*
* @param <K> The type of the key (must implement InverseInterpolable)
* @param <V> The type of the value (must implement Interpolable)
*/
public class InterpolatingTreeMap<K extends InverseInterpolable<K> & Comparable<K>, V extends Interpolable<V>>
extends TreeMap<K, V> {
private static final long serialVersionUID = 8347275262778054124L;
final int max_;
public InterpolatingTreeMap(int maximumSize) {
max_ = maximumSize;
}
public InterpolatingTreeMap() {
this(0);
}
/**
* Inserts a key value pair, and trims the tree if a max size is specified
*
* @param key Key for inserted data
* @param value Value for inserted data
* @return the value
*/
@Override
public V put(K key, V value) {
if (max_ > 0 && max_ <= size()) {
// "Prune" the tree if it is oversize
K first = firstKey();
remove(first);
}
super.put(key, value);
return value;
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
System.out.println("Unimplemented Method");
}
/**
* @param key Lookup for a value (does not have to exist)
* @return V or null; V if it is Interpolable or exists, null if it is at a bound and cannot average
*/
public V getInterpolated(K key) {
V gotval = get(key);
if (gotval == null) {
// get surrounding keys for interpolation
K topBound = ceilingKey(key);
K bottomBound = floorKey(key);
// if attempting interpolation at ends of tree, return the nearest data point
if (topBound == null && bottomBound == null) {
return null;
} else if (topBound == null) {
return get(bottomBound);
} else if (bottomBound == null) {
return get(topBound);
}
// get surrounding values for interpolation
V topElem = get(topBound);
V bottomElem = get(bottomBound);
return bottomElem.interpolate(topElem, bottomBound.inverseInterpolate(topBound, key));
} else {
return gotval;
}
}
}