Data structures that can map a range of keys to a value

后端 未结 7 2047
死守一世寂寞
死守一世寂寞 2020-11-27 18:02

I am trying to find a data structure that takes in a particular value from a range of values and map it to a key.

For example, I have the following conditions:

7条回答
  •  无人及你
    2020-11-27 18:42

    A HashMap will not work for mapping ranges to values unless you find a way to generate a hashcode for ranges and single values in there that matches. But below approach could be what you are looking for

    public class RangeMap {
        static class RangeEntry {
            private final double lower;
            private final double upper;
            private final Object value;
            public RangeEntry(double lower, double upper, Object mappedValue) {
                this.lower = lower;
                this.upper = upper;
                this.value = mappedValue;
            }
            public boolean matches(double value) {
                return value >= lower && value <= upper;
            }
            public Object getValue() { return value; }
        }
    
        private final List entries = new ArrayList();
        public void put(double lower, double upper, Object mappedValue) {
            entries.add(new RangeEntry(lower, upper, mappedValue));
        }
        public Object getValueFor(double key) {
            for (RangeEntry entry : entries) {
                if (entry.matches(key))
                    return entry.getValue();
            }
            return null;
        }
    }
    

    You could do

    RangeMap map = new RangeMap();
    map.put(1, 2.9, "A");
    map.put(4, 6, "B");
    
    map.getValueFor(1.5); // = "A"
    map.getValueFor(3.5); // = null
    

    It's not very efficient since it's just iterating over a list and it will in that state not complain if you put conflicting ranges in there. Will just return the first it finds.

    P.S.: mapping like this would be mapping a range of keys to a value

提交回复
热议问题